How to easily change a font-sizing from px to em f

2019-04-12 17:55发布

How to easily change a font-sizing from px to em for a big, existing site?

Any tips to do this quickly?

标签: css xhtml
2条回答
我只想做你的唯一
2楼-- · 2019-04-12 18:33

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).

Potential Problems

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) × .625 (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.

Approach

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. I prefer to 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.

Some people set body to 0.625em because that equals 10px (16 × 0.625 = 10), meaning for elements that don’t have an ancestor with a set font size, 1em = 10px, 1.1em = 11px and so on. Personally, I think that adds more complexity than it removes, but I’ve never done a comparison.

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.

查看更多
Deceive 欺骗
3楼-- · 2019-04-12 18:36
  1. Open css file
  2. Search for px, look at how many different sizes are there
  3. Decide on a conversion e.g. 10px =.5em, 12px=1em
  4. Search/replace each size
查看更多
登录 后发表回答