Search code examples
cssgridcss-grid

Remove spaces caused by grid rows by using elements with variable heights


This is the basic layout of the page:

* {
  margin: 0;
  padding: 0;
}

img {
  width: 100%;
  float: left;
}

#grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

#test-one {
  grid-column-start: 1;
  grid-column-end: 2;
  width: 100%;
  height: 300px;
}

#test-two {
  grid-column-start: 2;
  grid-column-end: 3;
  width: 100%;
}

#test-three {
  grid-column-start: 2;
  grid-column-end: 3;
  width: 100%;
}
<div id="grid">
  <div id="test-one"><img src="https://upload.wikimedia.org/wikipedia/commons/9/97/Feral_cat_Virginia_crop.jpg"></div>
  <div id="test-two">
    <h2> Hello </h2>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna.</div>
  <div id="test-three">
    <h2>Please no gap to top text with the "Hello" headline</h2>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo
    dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. </div>
</div>

The image will have a specific height. The text areas have a dynamic height based on the text. Between the text blocks with the IDs #test-two and #test-three shouldn't be a vertical gap. Can this be fixed with a few CSS settings? Or does the layout need to be reorganzied?

Addition: I think working with grid-row settings doesn't help here much since the heights are variable. Let me know if I am wrong.


Solution

  • from my comment

    You can either span .test-one through 2 rows (see grid-row: xx;) in your favorite grid tutorial) , take a look at masonry grid (here in the search) or even use column CSS if that's fine for you. – G-Cyrillus 1 min

    here an example via grid-row-start/end like you did for column :

    #grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-column-gap: 10px;
    }
    
    #test-one {
      grid-column-start: 1;
      grid-column-end: 2;
      background-color: red;
      grid-row-start: 1;
      grid-row-end:3;
      height: 100px;
      width: 100%;
    }
    
    #test-two {
      grid-column-start: 2;
      grid-column-end: 3;
      background-color: blue;
      height: 50px;
      width: 100%;
    }
    
    #test-three {
      grid-column-start: 2;
      grid-column-end: 3;
      background-color: green;
      height: 50px;
      width: 100%;
    }
    <div id="grid">
      <div id="test-one">Hello Box</div>
      <div id="test-two">Hey Box</div>
      <div id="test-three">Please no top gap to the "Hey Box"</div>
    </div>