Pixels and rems and ems and percents, oh my.
While there are several different methods for coding with font sizes, it all depends on what’s right for your particular project.
First Things First
Let’s take a closer look at every option:
- Pixels: font-size: 16px shows as 16 pixels in the browser.
- Rem: font-size: 1rem shows the pixel size set on the page’s root element, html. So if the html element is set to 16px, 1rem renders as 16 pixels in the browser.
- Em: font-size: 1em shows the pixel size relative to what it inherits from its parent element. This works similarly to rem in that it is a percentage of the parent, but instead of being influenced by the root, it’s influenced by its parent container – which can get tricky if that’s also nested within a grandparent container with a font-size value.
- Percent: works very much like an em in that if the parent is set to 16px, 100% will render as 16 pixels in the browser.
3 Methods to Consider
While there are a multitude of strategies for combining these to fit a project’s requirements, here are a few to consider:
1. Tried-and-true: 62.5% and ems
This method has been around for a while, and it’s a tried-and-true method for making em sizes easier to calculate. By setting the body to 62.5%, 1em becomes 10 pixels, 1.5em becomes 15 pixels, and so on. It’s easy to write precise font sizes with this method as it has a simple 1 to 10 ratio.
2. Combination of pixels, rems, and ems
This strategy was set forth by CSS Tricks for module-based sites, and it uses pixels as the base on the html element, rems on the module containers and ems for the text. The advantage of this method is that a module container’s font-size can be set with the result that it proportionally shrinks or enlarges the font size. For instance, a sidebar module container can be given a font size to proportionally shrink all the text inside it from <h1> to <p> to <span>.
3. Bootstrap in the mix
Bootstrap uses a mix of pixels, ems and percents for their font-sizes.
- The html is set to 10 pixels, presumably to set 1rem to 10 pixels to make rems easy to calculate.
- The body is set to 15 pixels, a standard size for paragraph text.
- Standard text elements like h1 and p are set with ems.
- Font variants such as small are set with percentages such as 75%. Their heading classes (.h1, h2, h3, etc.), form input classes, and text class, .lead, are set with pixel sizes to ensure that, regardless of where they are nested within the site, they will take on the intended size instead of possibly inheriting an em size from its parent.
So which method is the best? It honestly depends on the project. Every project requires its own approach. Go where the project leads, and don’t be afraid to explore. And if you have any questions, let us know. We’d love to help!