January 14, 2012
CSS Sizing Advice: %, REMS, and EMs
An interesting blog post – Measuring and sizing UIs, 2011-style — over at CSS Wizardry provides up-to-date advice for CSS measurements. In a nutshell, the post advises web designers to abandon pixel values except in a few cases (like CSS-sprites), and use %, Rems, or ems. In particular it suggests:
- Use percentages for structural elements (like sidebars, headers, footers, main content). I still think pixels can be valuable for constraining designs on giant monitors using the max-width property. For example:
.wrapper {
max-width: 1240px;
}
- Use rems for type. (Not up on the rem value? Check out this simple intro on Font-sizing with rem).
- Use ems for type-related properties (like margins, padding) so they scale with the type size.
- Use unit-less values for line-height.
- Avoid measurements entirely, if possible. For example, you don’t need to set the width of an element that you want to match the size of its container. If the container has a set value, then then any block-level element inside it already stretches to fit.
My biggest issue with percentage based layouts is that the floats fall apart when they contain an image. If the browser resolution isn’t high enough, there’s not enough room for the picture, for example when the user resizes the browser window.
That’s a good point, and with mobile devices (and smaller screens) becoming more common the situation you describe is easy to get into. One of the most popular solutions to this problem now is “Responsive Web Design.” Using a combination of CSS media queries, flexible grids (that’s the percentage-based layout stuff), and flexible images and media you can address the problem with images not fitting within smaller screen sizes. Sitepoint has a basic introduction to responsive web design. See The Boston Globe web site for an example of responsive web design (make sure you resize your browser window so that it’s as thin as it can get.)