Search code examples
csscss-grid

How to overlap image tag as a background over two CSS Grid areas


The image is an img tag and needs to be stretched as a background image over two areas 'img' and 'content'. The text has to go above the stretched image in the 'content' area. Simple but how? I can't find any obvious answers online.

.media {
    border: 2px solid #f76707;
    border-radius: 5px;
    background-color: #fff4e6;
    width: 100%
}
.media {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-areas: "img content";
    margin-bottom: 1em;
}

.image {
    grid-area: img;
    background-color: #ffd8a8;
}

.text {
    grid-area: content;
    padding: 10px;
}
<div class="media">
    <img class="image" src="https://loremflickr.com/500/200" />
    <div class="text">This is a media object example. 
      We can use grid-template-areas to switch around the image and text part of the media object.
    </div>
</div>


Solution

  • Modify your code as follows:

    .media {
      border: 2px solid #f76707;
      border-radius: 5px;
      background-color: #fff4e6;
      width: 100%
    }
    
    .media {
      display: grid;
      grid-template-columns: 1fr 1fr;
      grid-template-areas: "img content";
      margin-bottom: 1em;
    }
    
    .image {
      grid-area: img;
      background-color: #ffd8a8;
    }
    
    .text {
      grid-area: content;
      padding: 10px;
    }
    
    .media {
      background-image: url("https://loremflickr.com/700/200");
      background-repeat: no-repeat;
      height: 150px;
    }
    <div class="media">
      <div class="text">This is a media object example. We can use grid-template-areas to switch around the image and text part of the media object.
      </div>
    </div>

    Here is a screenshot of the output:

    enter image description here