You should never (hardly) ever set heights in CSS

If you find yourself setting heights on elements more often than not in CSS, take a step back, because you’re (most likely) doing something wrong, and down the road you’re going to hate yourself for it.

It’s one of the more common ‘css design faux pas’ that I have encountered as a web developer, and to me just demonstrates a lack of understanding about how box model elements behave. 99% of the time heights should be left inherit - locking yourself into a height can quickly bring limitations to your site layout, provide a maintenance nightmare, and they’re almost never needed.

By default, an element will be as tall as the elements/content that are inside it. A few cases which might cause a container’s height to collapse are if your internal elements are floated, or if they are absolutely positioned. In both of these cases, the easy answer is to set a height on the collapsed element and forget about it. However, this isn’t really good practice, and you’re basically treating the symptoms and not the cause.

If you’re losing height because of floated elements - clear them, either by using an overflow property on the containing element or doing a good ol’ fashioned clear div.

Absolutely positioned elements can be a bit trickier, since the whole point of them is to not have layout space, so heights are acceptable, however I like to use padding whenever I can, just to avoid being locked into a set height.

Hopefully these tricks will be useful to someone, and make CSSing a bit more flexible and fun.

0 Responses to “You should never (hardly) ever set heights in CSS”


  1. No Comments

Leave a Reply