Aligning an element to the bottom of its container
Here is a little CSS trick that allows you to align content to the bottom of its container, in a similar fashion to how vertical-align="bottom"
works in table-based layouts.
Let’s say we want to display an image with a title aligned to its top right corner, and a caption aligned to its bottom right corner:
Here is the CSS:
.portfolioImg {
float:left;
margin-right: 20px;
}
.imgDetails {
position: relative;
float:left;
height: 280px;
width: 150px;
}
.imgDetails p {
position: absolute;
bottom: 0;
}
Here is the markup:
<img class="portfolioImg" src="monster.jpg" width="280" height="280" alt="Knitted monster" />
<div class="imgDetails">
<h2>Image title</h2>
<p>This is the image caption. It is aligned to the bottom of its containing element.</p>
</div>
The trick is to set the position
of the container to relative
, and the position
the of the child element to absolute
. Then set the child’s bottom
property to 0
.
Photo credit
The photo of the cute knitted critter in my example is by Tamie Snow. You can learn more about her wonderful knitted creations at Roxycraft.
5 thoughts on “Aligning an element to the bottom of its container”
Comments are closed.
Sometimes it’s really that simple, isn’t it? I feel a little stupid for not thinking of this myself/earlier, though.
Cheers for this! Super simple!
An alternative if you were working with dynamically generated images with variable heights would be to use a wrapper div around both image and the caption, float the image left and absolutely position the caption to the bottom (as currently), but instead of specifying a height for caption or the wrapper div, define overflow: hidden on the wrapper, so it will automatically stretch to the height of the floated image and thereby align the caption correctly.
@Jaitra – A very good suggestion!
@Jaitra could you please show a code example of your solution cause that’s the situation I’m in and I can’t solve the problem? Thank you.