Equal height HTML elements in a container with CSS

Task: create HTML elements that contain other elements and adjust their height to surrounding container. No Javascript allowed.

That’s surprisingly hard; height:100% won’t work; elements generally wrap their contents tightly and don’t extend to their parents height dimension.

Illustrating the problem: three elements inside a surrounding container

Css-tricks lists several ways [1] to get this done, two of which caught my attention for either their elegance or novelty.

Flexbox

The first technique uses the CSS3 flexbox attribute [2] which is good for all kind of alignment jobs and genuinely solves the problem by making child elements extend to the height of the parent container.

Child elements extending to parent height with flexbox layot

The solution is as simple as it is elegant and requires only a few settings at the parent container:

.parent{
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
overflow: hidden;
}

Infinite padding

Css-tricks describes the “one true layout” technique which uses a large padding, compensated with an equally large but opposite margin. The idea is that the children elements will extend through a large, negative bottom margin far beyond the end of the container, but their content will be compressed back into the original size with an equally large positive bottom padding. The parent uses a hidden overflow setting so that the infinite, overflowing part of the contained children is cropped off.

The infinite padding technique

The css used:

.parent{
overflow: hidden;
}

.parent .column{
margin-bottom: -99999px;
padding-bottom: 99999px;
}

This technique works also on pre-CSS3 browsers but has a catch illustrated in the picture above: CSS element borders will extend, of course, to infinity which limits the technique’s usefulness to opaque, borderless boxes.

Resources

[1] Fluid Width Equal Height Columns
https://css-tricks.com/fluid-width-equal-height-columns/

[2] CSS flexible box layout
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s