How to align a div to the top of its parent but keeping its inline-block behaviour?
In essence, you need to use the vertical-align: top;
property on a div
that has been set to display as inline-block;
. This way, it will align to the top of its containing element, while maintaining its inline-block behaviour.
The CSS here will align the div
along the top-axis of its containing element but will still keep the div
's inline layout.
Dissecting vertical-align and inline-block properties
The vertical-align
CSS property is your magician's wand when it comes to determining the vertical alignment of an element which displays as inline
or table-cell
.
With display: inline-block;
, this little trick is a lifesaver for controlling the vertical alignment without meddling with the elements' horizontal order.
A few noteworthy things here:
vertical-align
applies only to inline or table-cell elements, not block level.- By default, elements align along the baseline leading to sneaky white space.
- Employing
vertical-align: top;
aligns the top of inline-block elements along the line box's top edge.
For your convenience, here's a snippet illustrating the difference:
The many faces of vertical-align
Lucky for us, vertical-align
has several other values as well:
middle
: Aligns the vertical midpoint of the child with the baseline plus half the x-height of its parent.bottom
: Aligns the bottom of the box with the bottom of the lowest element in the line.text-top
: Aligns top of the box with the top of the parent's font.text-bottom
: Aligns the bottom of the box with the bottom of the parent's font.
The key here is to experiment with these values to understand which suits your requirement best.
Alternatives and compatibility checks
Thought vertical-align: top;
was the only way out? Wrong! Dive in for some alternatives.
The good old float property
float: left;
can give you the same top alignment, except when you've decided to time travel and need to deal with older browsers:
Dropping in with flexbox
For modern layouts, Flexbox has been a godsend:
Grid layout - next level control
CSS Grid Layout offers control with a capital C:
Interaction with layout and quirks
Before we apply any method, let's bear in mind a few considerations:
- Browser compatibility: Be wary if supporting legacy browsers. Those are like moody old folks!
- Rendering differences: Because not all browsers are made equal, unfortunately.
- Parent's height: This can impact the alignment of your child elements.
- Inline-block whitespace issue: Sneaky white spaces between inline elements can take you by surprise!
Make sure to test on multiple browsers and devices to ensure consistency.
Was this article helpful?