Units of measurement
Various units of measurement exist in CSS, allowing for documents to be designed appropriately for varying formats whether digital or in print.
Numerical units
Various numerical units exist in CSS for setting the size of an element or its content, these include:
- integer: Whole numbers, negative or positive
- number: A decimal number, commonly seen used with
line-height
- dimension: A number with a unit attached, such as
10px
for 10 pixels - percentage: Represents a fraction of some value, always relative to some other quantity; usually a value from a parent element.
Lengths
Setting the length of some content is the most common usage of the numerical units, there are two types of length in CSS: relative and absolute
Absolute units
Absolute units represent a specific size and are not based relatively from some other inherited property, some of which include:
cm
: Represents centimetres, 1cm = 37.8px = 25.2/64inin
: Represents inches, 1in = 2.54cm = 96pxpt
: Represents points, 1pt = 1/72nd of 1inpx
: Represents pixels, 1px = 1/96th of 1in
The most commonly used absolute unit is pixels, this is because it is designed for the digital format. The majority of the absolute units though are used for representing lengths in print (text you would print out to physical mediums).
Relative units
Relative units get their size through relating to the size of something else, such as a parent elements font size or the width of an element. Relative units allow you to adjust the size of content based on the size of something else, extremely useful in creating responsive designs. Some of these units include:
-
em
: Specifies a size relative to the font-size of a parent element when used with for typographical properties. If used with properties likewidth
orheight
, it is based off of the font size of the element being applied to. rem
: Specifies a size relative to the font size of the root element (html
)vw
: Specifies a size relative to the viewports width, the viewport being the visible area of the browser window where a page is displayed. 1vw = 1% of the viewports widthvh
: Similar tovw
, but relative to the viewport height instead.
The following example demonstrates the usage of the px
, em
and rem
units:
The root element (html
) has a 10px
font-size. This paragraph of text is 3 times as large (3rem
) giving it a size of 30px
.
This paragraph of text is set to 0.5em
, that is the size of the containers text (20px
) divide 2, i.e., 10px
.