CSS Units
- Previous Page CSS Website Layout
- Next Page CSS Specificity
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 at this size.
It is not recommended to use absolute length units on the screen because screen sizes vary greatly. However, if the output medium is known, they can be used, such as for print layout (print layout).
Unit | Description | TIY |
---|---|---|
cm | Centimeter | Try It |
mm | Millimeter | Try It |
in | Inch (1in = 96px = 2.54cm) | Try It |
px * | Pixel (1px = 1/96th of 1in) | Try It |
pt | Point (1pt = 1/72 of 1in) | Try It |
pc | Pica (1pc = 12 pt) | Try It |
* 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 | Font size relative to the element (font-size) (2em means twice the current font size) | Try It |
ex | X-height relative to the current font (rarely used) | Try It |
ch | Width relative to "0" (zero) | Try It |
rem | Font size relative to the root element (font-size) | Try It |
vw | 1% of the viewport* width | Try It |
vh | 1% of the viewport* height | Try It |
vmin | 1% of the viewport* smaller size | Try It |
vmax | Relative to the viewport's *larger size* by 1% | Try It |
% | Relative to the parent element | Try It |
Tip:em and rem units can be used to create perfect scalable layouts!
* Viewport (Viewport) = Size of the browser window. If the viewport is 50 centimeters wide, then 1vw = 0.5 centimeters.
Browser Support
The numbers in the table indicate the first browser version that fully supports this 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 Website Layout
- Next Page CSS Specificity