Site logo

Archived topic

Align last item of grid to the bottom

3 replies · Started by mkjj on July 7, 2022

Viewing posts 1–4 of 4

Hi there,
I'm pulling my hair out about a pretty common problem that I am unable to solve. I use a very simple grid to show some elements on a page.

The HTML structure is quite straighforward:


<div class="grid">
<div>
<p>Image</p>
<p class="heading">Heading</p>
<p>Text</p>
<p>Button</p>
</div>
</div>

CSS:


.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
.grid div {
  margin: 1em;
  padding: 0.5em;
}
.grid p {
  text-align: center;
  margin: 0;
  font-size: 1rem;
}
.grid p:first-of-type {
  margin-bottom: 1em;
}
.grid p:last-of-type {
  margin-top: 1em;
}

The text might vary so that I want the buttons to be aligned at the bottom. I tried David's suggestion in this post.

This works, but it creates a very large gap between the button and the text block. Can somebody point me in the right direction? I could easily change the inner structure of the grid items since everything is created manually.

Thank you very much in advance.

Hi there,

you could just do this:

.grid > div {
    display: flex;
    flex-direction: column;
}
/* push last element down */
.grid > div > :last-child {
    margin-top: auto;
}
/* add bottom margint to element before last */
.grid > div > :nth-last-child(2) {
    margin-bottom: 20px;
}

Hi David,
simply awesome! Works like a charm. :-) You ALWAYS exceed my expectations. I really appreciate your support even for questions like this that was not GP-related. I really tried to find a solution, but wasn't successful.

Thanks again, Mike

I am happy to hear that :)

This archived topic is closed to new replies.