Search code examples
csscss-grid

Image pushing divs below


I have a 2 column layout with an image to the left and wanted to have 3 divs on the right but can only manage to get 1 div to align next to the image and the other 3 divs are below the image. How can I have all 3 divs next to the image?

I know this is easy with grid-areas but wanted to do it with out.

.wrapper {
  background-color: pink;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: auto auto 1fr;
}

.hero {
  background-color: red;
}

.foo {
  background-color: orange;
}

.bar {
  background-color: lime;
}

.baz {
  background-color: aqua;
}

img {
  width: 100%;
  display: block;
}
<div class="wrapper">
  <div class="hero">
    <img src="https://via.placeholder.com/1080x1080" alt="">
  </div>
  <div class="foo">
    foo
  </div>
  <div class="bar">
    bar
  </div>
  <div class="baz">
    baz
  </div>
</div>

https://codepen.io/emmabbb/pen/oNqPwad


Solution

  • Set a specific grid row value on your hero: grid-row: 1 / 4;

    Like this:

    .wrapper {
      background-color: pink;
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      grid-template-rows: auto auto 1fr;
    }
    
    .hero {
      background-color: red;
      grid-row: 1 / 4;
    }
    
    .foo {
      background-color: orange;
    }
    
    .bar {
      background-color: lime;
    }
    
    .baz {
      background-color: aqua;
    }
    
    img {
      width: 100%;
      display: block;
    }
    <div class="wrapper">
      <div class="hero">
        <img src="https://via.placeholder.com/1080x1080" alt="">
      </div>
      <div class="foo">
        foo
      </div>
      <div class="bar">
        bar
      </div>
      <div class="baz">
        baz
      </div>
    </div>

    If you want your divs with text in them to be of equal height change the grid template rows to grid-template-rows: 1fr 1fr 1fr; Like this:

    .wrapper {
      background-color: pink;
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      grid-template-rows: 1fr 1fr 1fr;
    }
    
    .hero {
      background-color: red;
      grid-row: 1 / 4;
    }
    
    .foo {
      background-color: orange;
    }
    
    .bar {
      background-color: lime;
    }
    
    .baz {
      background-color: aqua;
    }
    
    img {
      width: 100%;
      display: block;
    }
    <div class="wrapper">
      <div class="hero">
        <img src="https://via.placeholder.com/1080x1080" alt="">
      </div>
      <div class="foo">
        foo
      </div>
      <div class="bar">
        bar
      </div>
      <div class="baz">
        baz
      </div>
    </div>