Search code examples
htmlcsscss-grid

Expanding background outside grid-area


I have created a template using CSS grid:

main {
  display: grid;
  grid-template-areas: '. content .' '. other-content .';
  grid-template-columns: 1fr 15em 1fr;
  grid-row-gap: 1em;
}

.content {
  background-color: blue;
  grid-area: content;
}

.content-bg-left,
.content-bg-right {
  background-color: blue;
}

.content-without-expanded-bg {
  background-color: green;
  grid-area: other-content;
}
<main>
  <div class="content-bg-left"></div>
  <div class="content">
    Something inside here
  </div>
  <div class="content-bg-right"></div>
  <div class="content-without-expanded-bg">
    Something else here
  </div>
</main>

What I don't like with the above setup is that there are empty elements hanging around. Is it possible to expand the background for .content element without the need for the empty .content-bg-left and content-bg-right elements? I still want .content to stay in the middle, so adding grid-column: 1/-1; is not an option.


Solution

  • Your solution is pretty fine. We can get rid of extra divs, but by just changing them on ::before and ::after. This solution is more like hack, but it works for this task.

    main {
      display: grid;
      grid-template-areas: '. content .' '. other-content .';
      grid-template-columns: 1fr 15em 1fr;
      grid-row-gap: 1em;
      overflow: hidden;
    }
    
    .content {
      background-color: blue;
      grid-area: content;
      position: relative;
    }
    
    .content::before,
    .content::after {
      content: '';
      background-color: blue;
      position: absolute;
      width: 9999px;
      height: 100%;
      top: 0;
    }
    
    .content::before {
      right: 100%;
    }
    
    .content::after {
      left: 100%;
    }
    
    .content-without-expanded-bg {
      background-color: green;
      grid-area: other-content;
    }
    <main>
      <div class="content">
        Something inside here
      </div>
      <div class="content-without-expanded-bg">
        Something else here
      </div>
    </main>