codelord.net

Code, Angular, iOS and more by Aviv Ben-Yosef

CSS Tip: DIVs with Equal Dynamic Heights

| Comments

Continuing my series of short CSS tips I’d like to share a trick I was taught by a friend a few years ago when we were working on some new layout for our web app.

One of the most annoying problems with CSS is that the height property is pretty limited in strength when it comes to setting it dynamically. I’d like to talk about a relatively simple problem: a 2 column layout where we don’t know how high each colum will be and we want both columns to have the same maximal height.

Since we don’t know the columns’ heights, we can’t set a fixed height on their parent. Also setting height: 100% or something like that on the columns won’t work: we are counting on them to spread to the maximum height and thus make their parent taller.

Cutting to the chase

Though there are more ways of doing this my favorite is relying on the magic properties of tables, or, more specifically, table-like elements.

The whole trick is making the two columns have the properties of two neighboring table cells, which always have the same height. Our HTML would look like this:

1
2
3
4
5
6
<div class="layout">
    <div class="columns-container">
        <div class="column"></div>
        <div class="column"></div>
    </div>
</div>

And the needed CSS is this:

1
2
3
4
5
6
7
8
9
10
11
.layout {
    display: table;
}

.layout .columns-container {
    display: table-row;
}

.layout .columns-container .column {
    display: table-cell;
}

That’s about it! And the nice part is that it’s actually not limited to 2 columns, you can have as many as you want ;)

A word of warning: some of you might try and see that it seems like this works withjust setting display: table-cell on the columns and without the rest of the styles. While that works on some browsers, from my personal experience that’s not compatible on all browsers and in general table-cell display is not supposed to be used outside the scope of a full “table simulating” structure.

I hope you learned something new. Happy coding!

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

Comments