CSS Units
- Previous Page CSS Font Fallback
- Next Page CSS Colors
CSS Units
CSS has several different units for representing length.
Many CSS properties accept 'length' values, such as width
,margin
,padding
,font-size
etc.
Length is a number followed by a length unit, such as 10px
,2em
etc.
Example
Set different length values using px (pixels):
h1 { font-size: 60px; } p { font-size: 25px; line-height: 50px; }
There should be no spaces between numbers and units. However, if the value is 0, the unit can be omitted.
For some CSS properties, negative lengths are allowed.
There are two types of length units:Absolute UnitsandRelative Units.
Absolute Length
Absolute length units are fixed, and the length represented by any absolute length will be displayed exactly this size.
It is not recommended to use absolute length units on the screen because the screen size varies greatly. However, they can be used if the output medium is known, such as for print layout (print layout).
Unit | Description | TIY |
---|---|---|
cm | Centimeter | Try it out |
mm | Millimeter | Try it out |
in | Inch (1in = 96px = 2.54cm) | Try it out |
px * | Pixel (1px = 1/96th of 1in) | Try it out |
pt | Point (1pt = 1/72 of 1in) | Try it out |
pc | Pica (1pc = 12 pt) | Try it out |
* Pixels (px) are relative to the viewing device. For devices with low dpi, 1px is one device pixel (dot) on the screen. For printers and high-resolution screens, 1px represents multiple device pixels.
Relative Length
Relative length units specify the length relative to another length property. Relative length units scale better between different rendering media.
Unit | Description | TIY |
---|---|---|
em | Relative to the font size of the element (font-size) (2em means twice the current font size) | Try it out |
ex | Relative to the x-height of the current font (rarely used) | Try it out |
ch | Relative to '0' (zero) in width | Try it out |
rem | Relative to the font size of the root element (font-size) | Try it out |
vw | 1% of the width relative to the viewport* | Try it out |
vh | 1% of the height relative to the viewport* | Try it out |
vmin | 1% of the smaller size relative to the viewport* | Try it out |
vmax | 1% of the larger size relative to the viewport* | Try it out |
% | Relative to the parent element | Try it out |
Tip:em and rem units can be used to create perfect scalable layouts!
* Viewport (Viewport) = the size of the browser window. If the viewport width is 50 inside, then 1vw = 0.5cm.
Browser Support
The numbers in the table indicate the first browser version that fully supports the length unit.
Length Units | |||||
---|---|---|---|---|---|
em, ex, %, px, cm, mm, in, pt, pc | 1.0 | 3.0 | 1.0 | 1.0 | 3.5 |
ch | 27.0 | 9.0 | 1.0 | 7.0 | 20.0 |
rem | 4.0 | 9.0 | 3.6 | 4.1 | 11.6 |
vh, vw | 20.0 | 9.0 | 19.0 | 6.0 | 20.0 |
vmin | 20.0 | 12.0 | 19.0 | 6.0 | 20.0 |
vmax | 26.0 | 16.0 | 19.0 | 7.0 | 20.0 |
- Previous Page CSS Font Fallback
- Next Page CSS Colors