How to put an item at the bottom of its container using CSS
By Flavio Copes
Learn how to put an item at the bottom of its container in CSS by giving the child position: absolute and bottom: 0, with position: relative on the parent.
To put an item at the bottom of its container, set position: absolute and bottom: 0 on the item, and position: relative on the container.
It’s a rather common thing to do, and I had to do it recently.
I was blindly assigning bottom: 0 to an element which I wanted to stick to the bottom of its parent. Nothing happened.
Turns out I was forgetting 2 things: setting position: absolute on that element, and adding position: relative on the parent.
Example:
<div class="card">
<p>The product description goes here.</p>
<button class="buy-button">Buy now</button>
</div>
.buy-button {
position: absolute;
bottom: 0;
}
.card {
position: relative;
}
Why do we need position relative on the parent?
The bottom property only works on positioned elements. That’s why my first attempt did nothing. An element with the default position: static ignores top, bottom, left and right entirely.
Once the element is absolutely positioned, it anchors to its nearest positioned ancestor. If no ancestor is positioned, it anchors to the page instead, and the button ends up at the bottom of the whole document. Not what we want.
Adding position: relative to the container makes it that anchor, without moving the container itself.
Making the item span the full width
By default an absolutely positioned element shrinks to fit its content. If you want it to stretch across the bottom of the container, add left: 0 and right: 0:
.buy-button {
position: absolute;
bottom: 0;
left: 0;
right: 0;
}
Watch out for overlapping content
Be careful with one thing: position: absolute removes the element from the normal flow. The container no longer reserves space for it, so it can overlap the content above it.
The fix is to give the container enough bottom padding to make room:
.card {
position: relative;
padding-bottom: 60px;
}
Set the padding to at least the height of the element you moved to the bottom.
If the container is already a flex column, there’s another option that keeps the element in the flow: give it margin-top: auto. The auto margin eats all the free vertical space and pushes the element down, with no overlap to worry about.
Related posts about css: