To position an HTML element to the bottom of its parent, you can do either of the following:
Using position: relative
on Parent and position: absolute
on the Child
In this approach, you need to do the following:
- Add
position: relative
to the parent; - Add
position: absolute
andbottom: 0
to the child; - Optionally, specify a
height
for the parent (it's not strictly necessary, but it's often useful); - Optionally, add
left: 0
to the child to align it with the left edge of the parent.
Consider, for example, the following where the child is positioned at the bottom of a fixed-height parent, and is unaffected by parent's padding
:
#child
position: absolute
bottom: 0
left: 0
Please note that this method is unaffected by changes to the parent's box sizing, but be cautious as the absolutely positioned child may overlap other content within the parent.
Using Flexbox
In this approach, you need to do the following:
- Set the parent container to
display: flex
andflex-direction: column
; - Apply
margin-top: auto
to the child element; - Optionally, specify a
height
for the parent (it's not strictly necessary, but it's often useful).
Consider, for example, the following where the child is positioned at the bottom of a fixed-height parent, but is affected by parent's padding
:
#child
margin-top: auto
Please note that this method adjusts to varying content heights within the parent but is affected by changes to the parent's box sizing, such as padding
.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.