Numerous CSS properties, including width, margin, padding, font-size, and others, accept “length” values.
A length comprises a numerical value followed by a unit of measurement, such as 10px, 2em, etc.
Example
Specify diverse length values using pixels (px).
h1 { |
Note: No whitespace is permitted between the number and the unit. Nonetheless, if the value is 0, the unit can be omitted.
Negative lengths are permissible for certain CSS properties.
Length units can be categorized into two types: absolute and relative.
Absolute length units are fixed and will render at precisely the specified size.
While absolute length units are not advised for screen use due to the variability of screen sizes, they can be suitable for scenarios where the output medium is predetermined, such as print layouts.
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) |
*Pixels (px) are relative to the viewing device. On low-dpi devices, 1px corresponds to one device pixel (dot) on the display. Conversely, for printers and high-resolution screens, 1px represents multiple device pixels.
Relative length units define a length relative to another length property, offering better scalability across various rendering mediums.
Unit |
Description |
em |
Relative to the font size of the element (2em means twice the size of the current font). |
ex |
Relative to the x-height of the current font (seldom used). |
ch |
Relative to the width of the “0” (zero) character. |
rem |
Relative to the font size of the root element. |
vw |
Relative to 1% of the width of the viewport* |
vh |
Relative to 1% of the height of the viewport* |
vmin |
Relative to 1% of the viewport’s* smaller dimension. |
vmax |
Relative to 1% of the viewport’s* larger dimension. |
% |
Relative to the properties of the parent element. |
Tip: Utilizing the em and rem units proves advantageous in crafting highly adaptable layouts! *Viewport refers to the size of the browser window. For instance, if the viewport measures 50cm in width, 1vw equals 0.5cm. |
Browser Support
The figures in the table indicate the initial browser version that comprehensively supports the length unit.