Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS How to Properly use ems instead of pixels?

Tags:

css

I'd like to try and convert my designs from pixels to ems. I've read so many tutorials that... and I'll leave it right there.

Starting with this as my base:

body {
    font-size: 62.5%;
    line-height: 1.4;
}

... now this is where I get lost...

Should I be defining my font-size like this:

div#wrapper { font-size: 1.5em; }

... or like this:

blockquote, li, p, dt, dd, etc { font-size: 1.5em }

And then the next thing I don't really understand is where ELSE should I be using ems in addition to font-size and line-height? I will be using a fixed-width layout using 960.gs.

like image 954
Jeff Avatar asked Feb 28 '23 04:02

Jeff


2 Answers

line-height: 1.4em;

Probably isn't what you want. The line-height will stay at the same computed height for the size of an ‘em’ on that element, even when you change the font-size on a descendant element.

line-height has a special case where it allows a unitless number:

line-height: 1.4;

Which makes each descendant line-height depend on its own font-size rather than the ancestor's.

Should I be defining my font-size [on a wrapper or on many element types]?

Well that rather depends on what you're trying to do. With relative font-sizes it is generally best to keep the number of declarations down to a minimum, because they nest: that is, with your blockquote { font-size: 1.5em; }, if you put a blockquote inside a blockquote you'd get a font-size of 1.5*1.5=2.25em compared to the body font size. Is that what you want? Maybe, maybe not.

where ELSE should I be using ems

Anywhere you want the size of an element to respond to the user's preferred font-size. One common example would be something like:

#maintext {
    width: 60%;
    min-width: 8em;
    max-width: 40em;
}

to try to restrict text lines to a reasonable column width when doing liquid layout.

But if you are limiting yourself to a fixed-width layout it may not make sense to make element widths font-size-dependent.

like image 56
bobince Avatar answered Mar 07 '23 22:03

bobince


You may find How to size text using ems an interesting and helpful read. The thing that I try to remember is my conversion from ems to pixels.

In your example:

body {
  font-size: 62.5%;
  line-height: 1.4em;
}

1 em is equal to 10 pixels if the browser default text-size is 16px. The line height would then be equal to 14 pixels. Like bobince beings out, I would use a unitless line-height value.

To help you with your calculations, you can use an Em Calculator. It allows you to easily convert between ems and pixels.

like image 35
Zack The Human Avatar answered Mar 07 '23 22:03

Zack The Human