HTML and CSS Reference
In-Depth Information
As of mid-2012, these units are only used in the context of media queries. As an ex-
ample, an author can set a media block to be used only on displays that have higher
than 500dpi:
@media (min-resolution: 500dpi) {...}
Interestingly,
dppx
is not defined by the Media Queries module, but appears in the Units
and Values modules alongside
dpi
and
dpcm
, which are defined in Media Queries. What
this means for the future is by no means clear.
Relative Length Units
Relative units are so called because they are measured in relation to other things. The
actual (or absolute) distance they measure can change due to factors beyond their con-
trol, such as screen resolution, the width of the viewing area, the user's preference
settings, and a whole host of other things. In addition, for some relative units, their size
is almost always relative to the element that uses them and will thus change from ele-
ment to element.
em and ex units
First, let's consider
em
and
ex
, which are closely related. In CSS, one “em” is defined to
be the value of
font-size
for a given font. If the
font-size
of an element is 14 pixels,
then for that element,
1em
is equal to 14 pixels.
Obviously, this value can change from element to element. For example, let's say you
have an
h1
with a font size of 24 pixels, an
h2
element with a font size of 18 pixels, and
a paragraph with a font size of 12 pixels. If you set the left margin of all three at
1em
,
they will have left margins of 24 pixels, 18 pixels, and 12 pixels, respectively:
h1 {font-size: 24px;}
h2 {font-size: 18px;}
p {font-size: 12px;}
h1, h2, p {margin-left: 1em;}
small {font-size: 0.8em;}
<h1>Left margin = <small>24 pixels</small></h1>
<h2>Left margin = <small>18 pixels</small></h2>
<p>Left margin = <small>12 pixels</small></p>
When setting the size of the font, on the other hand, the value of
em
is relative to the
font size of the parent element, as illustrated by
Figure 3
.
Figure 3. Using em for margins and font sizing