How to easily change a font-sizing from px
to em
for a big, existing site?
Any tips to do this quickly?
How to easily change a font-sizing from px
to em
for a big, existing site?
Any tips to do this quickly?
It depends on your existing stylesheet, but it’s probably not going to be quick I’m afraid (assuming you want the site to look the same after you’re done).
When text is sized in pixels, the visual size of the text will be the same as what you put in the CSS. For example, the CSS p {font-size: 12px;}
will result in all <p>
tags having a font size of 12 pixels.
However, when text is sized in ems, the visual size is calculated relative to the font size of its nearest ancestor.
So, if you had the following CSS:
body {font-size: .625em;}
p {font-size: 1.2em;}
.header {font-size: 1.5em;}
And the following HTML:
<body>
<p>Paragraph</p>
<div class="header>
<p>Paragraph inside header</p>
</div>
</body>
Then the visual font size of the first paragraph would be 1.2 (paragraph’s size) * .75 (body’s font size) * 16 pixels (the default root font size of all modern browsers) = 12 pixels.
But the visual size of the second paragraph would be 1.2 (paragraph’s size) * 1.5 (.header
’s size) * .625 * 16 pixels = 18 pixels.
If you don’t have a lot HTML elements with different font sizes nested within each other, then you’re fine. But you’ll need to check that yourself in the HTML — it could be difficult to tell from the stylesheet alone, especially if it’s a big site.
In terms of approach, when sizing fonts in ems, it’s easiest if the design for your site doesn’t have too many different font sizes. You set the <body>
element to the most commonly used font size, e.g.
body {
font-size: .75em;/* 12px */
}
Then you only change from that when you need to, e.g.
h2 {
font-size: 1.5em; /* 16px */
}
Otherwise you can end up sizing and resizing a lot when nesting happens. This can be particularly annoying for e.g. <li>
s.
Of course, this approach only works if the design for the site doesn’t include lots of different font sizes.
Either way, I find it really helpful to put the intended visual font size in comments after each use of font-size
, as above. That way, you remember what font size the element was meant to be if it gets re-nested in the HTML.