How to avoid aligning the height of small elements with display: flex
While display: flex;
is a powerful CSS property for easy layout alignment, its default behavior can cause child elements to be height-aligned. If you want the height of the child elements to be free to match the content, you need to adjust the align-items
property.
Why are the heights of child elements aligned?
Flexbox automatically adjusts the alignment and size of child elements if the parent element has display: flex;
. By default, align-items: stretch;
is set, and the height of child elements is stretched to match the parent’s height whenever possible.
How to not align the height of child elements
To align the height of a child element with the content, use align-items: start; or
align-items: flex-start;
. This will position the child elements according to the height of the content and prevent them from being height-aligned.
.flex-container {
display: flex;
align-items: start; /* This prevents child elements from being height-aligned and aligns them on top */
}
.child {
padding: 10px;
border: 1px solid #ccc;
}
Other Methods
Another way is to use align-items: baseline;
to align with the baseline of the child element’s text. This is another useful property if you don’t want to align heights.
.flex-container {
display: flex;
align-items: baseline; /* align with the baseline of the child element's text */
}
Usage Example and Notes
The following is an example implementation of Flexbox with child elements with content of various heights. In this example, each child element is aligned based on its own content by align-items: start;
.
short contentThe element contains long content.
Medium content.