Search code examples
htmlcsscss-grid

CSS: Full width Background for new css grid


I am using the new css grid like this:

#site {
   display: grid;
   grid-template-columns: 10% 1fr 1fr 1fr 10%;
   grid-template-rows: 100px auto;
   grid-template-areas:
      ". header header header ."
      ". content content sidebar ."
}

So I have tow rows and 5 columns but only 3 columns with content. I'm using the dot in the template areas to define a white space. This results in having a 3 column layout with white space on the left and right side. If I place an element in a grid area that has a background color the white space left and right stays white (logically). What I want is a full width background (color) but I'm not really sure how to realise this. One option I have in mind is to have a second grid in the background that has the same columns and rows but not the white spaces and then I can fill it up with color but I think this is not best practice.


Solution

  • Best I have found is put the grid inside a container for a certain width to center the content. And have items you need to extend the background give a huge left/right padding, and same margin negative.

    Just be sure to give body an overflow-x: hidden;

    <div class="container">
       <div id="site">
           <div class="header"></div>
           <div class="content"></div>
           <div class="footer"></div>
       </div>
    </div>
    

    And the CSS:

    .container{
      width:1000px;
      margin: 0 auto; //
    }    
    #site {
      display: grid;
      grid-template-columns: 10% 1fr 1fr 1fr 10%;
      grid-template-rows: 100px auto;
      grid-template-areas:
         ". header header header ."
         ". content content sidebar ."
    }
    
    .header{
       background: red;
       padding: 0 3000px;
       margin: 0 -3000px;
    }
    
    body{
       overflow-x: hidden;
    }