CSS Units
CSS has several different units for expressing length.
Some properties that set CSS length include width, margin, padding, font-size, border-width, etc.
A length consists of a number and a unit, such as 10px, 2em, etc.
There should be no spaces between the number and the unit. If the length value is 0, the unit can be omitted.
For some CSS properties, the length can be negative.
There are two types of length units: relative and absolute.
Browser Support
The numbers in the table indicate the minimum browser version that supports the length unit.
Length Unit | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
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 | 9.0* | 19.0 | 6.0 | 20.0 |
vmax | 26.0 | Not Supported | 19.0 | Not Supported | 20.0 |
Note: Internet Explorer 9 supports vmin with the non-standard name vm.
Relative Lengths
Relative length units specify a length relative to another length property. Relative lengths are more suitable for different devices.
Unit | Description | Online Example |
---|---|---|
em | It describes the relative size to the font size applied to the current element, making it a relative length unit. The default browser font size is usually 16px, so 2em == 32px; | Try it |
ex | Depends on the height of the lowercase letter 'x' | Try it |
ch | The width of the digit '0' | |
rem | rem stands for root em. When rem is applied to non-root elements, it is relative to the root element's font size; when applied to the root element's font size, it is relative to its initial font size. | Try it |
vw | Viewport width, 1vw = 1% of the viewport width | Try it |
vh | Viewport height, 1vh = 1% of the viewport height | Try it |
vmin | The smaller of vw or vh | Try it |
vmax | The larger of vw or vh | Try it |
% |
| | Tip: What is the difference between rem and em? The difference is that when setting the font size with rem, it is still a relative size but relative only to the HTML root element. | | --- | --- |
Absolute Lengths
Absolute length units are fixed values that represent a real physical size. Absolute length units are determined by the output medium and are independent of the environment (monitor, resolution, operating system, etc.).
Unit | Description | Online Example |
---|---|---|
cm | Centimeters | Try it |
mm | Millimeters | Try it |
in | Inches (1in = 96px = 2.54cm) | Try it |
px * | Pixels (1px = 1/96th of 1in) | Try it |
pt | Points, approximately 1/72 of an inch; (1pt = 1/72in) | Try it |
pc | pica, approximately 12pt, 1/6 inch; (1pc = 12 pt) | Try it |
Pixels might be considered the best "device pixels," while these pixel lengths are unrelated to the screen pixels you see on your display. px is actually a unit measured by angle.