Home > Enterprise >  How do I get rid of the space at the bottom of the grid elements?
How do I get rid of the space at the bottom of the grid elements?

Time:11-08

I have this layout made with CSS grid.

enter image description here

It's adding extra space at the bottom of each element. I'd like the red background(grid cell) to take up the minimum height of it's content.

Something like:

grid-template-rows: <minimum height> <minimum height> <minimum height>;

How do I acheive this?

I know I can just change the HTML and make it easier but since the title comes first on smaller screens, I can't change the structure.

.container {
  display: grid;
  grid-template-areas: "image image title"
                       "image image desc-1"
                       "image image desc-2";
  gap: 1rem;
  width: 500px;
  margin: 0 auto;
}
.item {
  background: tomato;
}
.title {
  grid-area: title;
}
.image {
  grid-area: image;
}
.desc-1 {
  grid-area: desc-1;
}
.desc-2 {
  grid-area: desc-2;
}

.image img {
  display: block;
}
.title, .desc-1, .desc-2 {
  margin-block: 0;
}
<section >
  <h2 >Lorem ipsum</h2>
  <div >
    <img src="https://picsum.photos/300/200.jpg" />
  </div>
  <p >Lorem ipsum dolor sit amet.</p>
  <p >Sed ut perspiciatis unde.</p>
</section>

CodePudding user response:

Use 4 rows instead of 3. You can also simplify your code like below:

.container {
  display: grid;
  grid-template-columns: 2fr 1fr; /* size of columns */
  gap: 1rem;
  width: 500px;
  margin: 0 auto;
}
.item {
  background: tomato;
}
.image {
  grid-row: 1/span 4; /* placed at 1st row and takes 4 rows */
  grid-column: 1; /* places at 1st column */
}
.image img {
  display: block;
}
.title, .desc-1, .desc-2 {
  margin-block: 0;
}
<section >
  <h2 >Lorem ipsum</h2>
  <div >
    <img src="https://picsum.photos/300/200.jpg" />
  </div>
  <p >Lorem ipsum dolor sit amet.</p>
  <p >Sed ut perspiciatis unde.</p>
</section>

CodePudding user response:

Can you try this?

.tomato{
  max-height: min-content;
}

CodePudding user response:

You can use enter image description here

Update: If you want to have an equal amount of gap between your elements, then you can set the height of the image to zero:

.image {
  grid-area: image;
  height: 0;
}

enter image description here

Although, it will be better to restructure your HTML so put your right items in a new flex/grid container to avoid the image overflowing the container.

  • Related