Search code examples
csscss-gridemotioncss-in-js

How to structure a grid layout


So I'm having trouble with the following CSS:

const Content = styled("div")`
  grid-area: main;
  background-color: white;
  margin-top: 5px;
  margin-left: 20px;
  margin-right: 20px;
  display: grid;
  grid-template-areas:
    "contentHeader contentHeader contentHeader"
    "contentItem   contentItem   contentItem"
    "contentItem   contentItem   contentItem";
  /* grid-template-columns: 1fr; */
  /* grid-auto-columns: 33px;
  grid-auto-rows: 150px; */
  grid-gap: 10px;
`;

const ContentHeader = styled("h1")`
  grid-area: contentHeader;
  font-family: Roboto;
  font-style: normal;
  font-weight: bold;
  font-size: 32px;
  line-height: 40px;
  color: black;
`;

const ContentMain = styled("div")`
  grid-column: 1fr;
  grid-row: 1fr;
  background-color: red;
`;

I'm aiming for a layout which has the header on the top left, and then two rows.

The first row would have two columns, and the first item would be larger than the second. The second row would have one item which filled both columns.

Instead I get this:

CSS Example

I know the issue is likely in my grid-column line, but it'd be great if someone could point me in the right direction. Also, I don't understand why I have huge gaps between my header and the coloured grid items?

Thanks!


Solution

  • you need to name each one of your content items in template area: ex:

    grid-template-areas:
        "contentHeader contentHeader contentHeader"
        "contentItem1   contentItem1   contentItem2"
        "contentItem3   contentItem3   contentItem3";
    

    then in your contentItem1 add this to css:

    grid-area: contentItem1
    

    in contentItem2 div add this to css:

    grid-area: contentItem2
    

    finally in contentItem3 add this to css:

    grid-area: contentItem3
    

    this is css only demo:

    .grid {
      display: grid;
      grid-template-areas: "contentHeader contentHeader contentHeader" "contentItem1   contentItem1   contentItem2" "contentItem3   contentItem3   contentItem3";
      grid-gap: 10px
    }
    
    .header {
      grid-area: contentHeader;
      background-color: red;
      height: 50px
    }
    
    .item1 {
      grid-area: contentItem1;
      background-color: blue;
      height: 150px;
    }
    
    .item2 {
      grid-area: contentItem2;
      background-color: green;
      height: 150px;
    }
    
    .item3 {
      grid-area: contentItem3;
      background-color: yellowgreen;
      height: 150px;
    }
    <div class="grid">
      <div class="header"></div>
      <div class="item1"></div>
      <div class="item2"></div>
      <div class="item3"></div>
    </div>