Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I define CSS margins in pixels or ems? Why? When?

Tags:

We have a CSS file with some rules similar to the following:

.directory-result ul
{
    margin-top: 20px;
    width: 60em;

}

.about-text
{
    margin-top: 1em;
    margin-bottom: 1em;
}

Everything is working ok, but we're wondering specifically about the inconsistencies between the margin-top values. One is 20px and the other is 1em.

Which is the best one to go with? What are the points I should consider when deciding which to use? Thanks.

like image 254
DaveDev Avatar asked Jul 26 '10 08:07

DaveDev


2 Answers

em units are used for better scalability of the page when the size of the elements depend on the page's scale. It's especially important for old browsers (e.g. IE6) and mobile platforms.

px units are used for absolute values, while em is relative to the font size of the particular element. 1em means one font-line, e.g. you have a box with font-size 12px that means that 1em will be equal to 12px

Also, using px seems easier because you know the exact value, but em units inherit the value of their container.

<p>Text</p>
<div class="box">
  <p>Lorem</p>
</div>

p {
  font-size: 1.2em;
}

.box {
  font-size: 1.2em;
}

In this case, the first <p> will have font-size equal to the basic font-size * 1.2, and the second <p> will display with font-size * 1.2 * 1.2.

like image 134
fantactuka Avatar answered Nov 15 '22 11:11

fantactuka


They're simply two different ways of measuring. Em is linked to the font size (traditionally, 1em is roughly the width of the letter M in a given typeface), while px is pixels.

If you build everything using em, everything will scale accordingly when the user adjusts their font size (e.g. using IE's Page > Text Size menu). It also makes it easier to work to a vertical rhythm.

Pixels are better when you want to build something "pixel-perfect". Be aware that a CSS pixel doesn't always equal a screen pixel - mainly because modern browsers and mobile devices allow for zooming. This isn't usually a problem though because the entire page is scaled accordingly.

Whatever you do, make sure you're consistent throughout - it makes life much easier later on.

like image 31
Olly Hodgson Avatar answered Nov 15 '22 10:11

Olly Hodgson