CSS Units
CSS Units
There are multiple units in CSS that can be used to describe length.
“Length” values are required for several CSS properties, including font-size, margin, padding, and width.
Length is expressed as a length unit, such as 10px, 2em, etc., followed by a number.
Example
Set different length values, using px (pixels):
h1 {
font-size: 60px;
}
p {
font-size: 25px;
line-height: 50px;
}
Note: There cannot be a gap between the unit and the number. On the other hand, the unit can be omitted if the value is 0.
Negative lengths are permissible for certain CSS properties.
Absolute and relative length units are the two varieties available.
Absolute Lengths
A length specified in any of these units will appear to be precisely that size since the absolute length units are fixed.
Because screen sizes vary so greatly, using absolute length units on a screen is not recommended. They can be utilized, nevertheless, if the output medium is known—for example, in print layout.
| Unit | Description |
|---|---|
| cm | centimeters |
| mm | millimeters |
| in | inches (1in = 96px = 2.54cm) |
| px * | pixels (1px = 1/96th of 1in) |
| pt | points (1pt = 1/72 of 1in) |
| pc | picas (1pc = 12 pt) |
* In terms of the viewing device, pixels (px) are relative. One device pixel (dot) on a low-dpi device is one px. One pixel represents many device pixels for printers and high-resolution screens.
Relative Lengths
A length is specified in relation to another length property using relative length units. Units of relative length scale more smoothly across various rendering mediums.
| Unit | Description | |
|---|---|---|
| em | Relative to the font-size of the element (2em means 2 times the size of the current font) | Try it |
| ex | Relative to the x-height of the current font (rarely used) | Try it |
| ch | Relative to width of the "0" (zero) | Try it |
| rem | Relative to font-size of the root element | Try it |
| vw | Relative to 1% of the width of the viewport* | Try it |
| vh | Relative to 1% of the height of the viewport* | Try it |
| vmin | Relative to 1% of viewport's* smaller dimension | Try it |
| vmax | Relative to 1% of viewport's* larger dimension | Try it |
| % | Relative to the parent element | Try it |
Advice: The em and rem units are useful for designing layouts that are precisely scalable!
* The browser window’s size is the viewport. 1vw = 0.5cm if the viewport is 50 cm wide.
Browser Support
The numbers in the table specify the first browser version that fully supports the length unit.