CSS offers various units for specifying lengths.
Many CSS properties, including width
, margin
, padding
, and font-size
, require length values.
A length value consists of a number followed by a unit, such as 12px
or 4em
.
Length in Pixels
You can specify different length values using pixels (px).
h1 {
font-size: 24px;
}
p {
font-size: 16px;
}
Note: There should be no whitespace between the number and the unit. However, if the value is 0
, the unit can be omitted.
Some CSS properties also allow negative lengths.
Length units in CSS are classified into two types: absolute and relative.
Absolute Lengths
Absolute length units are fixed, meaning a length specified in these units will appear as precisely that size.
While absolute length units are generally not recommended for screen use due to varying screen sizes, they can be appropriate for scenarios where the output medium is known, such as in 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 a single device pixel (dot). On high-DPI screens and printers, 1px represents multiple device pixels.
Relative Lengths
Relative length units define a length in relation to another length property. They adapt more effectively across various rendering mediums.
Unit Descriptionem
Relative to the font size of the element (e.g., 2em is twice the size of the current font).ex
Relative to the x-height of the current font (rarely used).ch
Relative to the width of the "0" (zero) character in the current font.rem
Relative to the font size of the root element.vw
Relative to 1% of the viewport's width.vh
Relative to 1% of the viewport's height.vmin
Relative to 1% of the viewport's smaller dimension.vmax
Relative to 1% of the viewport's larger dimension.%
Relative to the size of the parent element.
Note: The em and rem units are useful for creating layouts that scale perfectly. Viewport refers to the browser window size. For example, if the viewport is 50cm wide, then 1vw equals 0.5cm.