CSS Units
CSS Units
Example
Set different length values, using px (pixels):
h1 {
font-size: 60px;
}
p {
font-size: 25px;
line-height: 50px;
}
Try it Yourself »
Note: A whitespace cannot appear between the number and the unit. However,
if the value is 0, the unit can be omitted.
Absolute Lengths
The absolute length units are fixed and a length expressed in any of these will
appear as exactly that size.
Absolute length units are not recommended for use on screen, because screen
sizes vary so much. However, they can be used if the output medium is known,
such as for print layout.
Unit Description
cm centimetersTry it
mm millimetersTry it
* Pixels (px) are relative to the viewing device. For low-dpi devices, 1px is one
device pixel (dot) of the display. For printers and high resolution screens 1px
implies multiple device pixels.
Relative Lengths
Relative length units specify a length relative to another length property.
Relative length units scale better between different rendering medium.
Unit Description
Relative to the font-size of the element (2em means 2 times the size of the
em current font) Try
<!DOCTYPE html> it
<html>
<head>
<style>
p{
font-size: 16px;
line-height: 2em;
}
div {
font-size: 30px;
border: 1px solid black;
}
span {
font-size: 0.5em;
}
</style>
</head>
<body>
<p>These paragraphs have a calculated line-height of: 2x16px = 32px.</p>
<p>These paragraphs have a calculated line-height of: 2x16px = 32px.</p>
<p>These paragraphs have a calculated line-height of: 2x16px = 32px.</p>
<div>The font-size of the div element is set to 30px. <span>The span element
inside the div element has a font-size of 0.5em, which equals to 0.5x30 =
15px</span>.</div>
</body>
</html>
span {
font-size: 1ex;
}
</style>
</head>
<body>
<div>The font-size of the div element is set to 30px. <span>The span element
inside the div element has a font-size of 1ex</span>.</div>
</body>
</html>
Tip: The em and rem units are practical in creating perfectly scalable layout!
* Viewport = the browser window size. If the viewport is 50cm wide, 1vw =
0.5cm.