CSS Units and Values

Overview

This page describes some of the values and units that CSS properties accept. Most of the properties and values listed are taken from specifications that have achieved "Recommendation" status, i.e. the Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification which achieved recommendation status in June 2011, and the CSS Basic User Interface Module Level 3 (CSS3 UI) which achieved recommendation status in June 2018.

As you will by now be aware, every CSS rule consists of three components. The first component is a selector that identifies the HTML element (or elements) that the rule applies to. The selector is followed by a declaration block containing the two remaining components: a property, and the value that is assigned to that property. The general form of a CSS rule is thus as follows:

selector { property: value }

The kind of value that can be assigned to a property will very much depend on the property. For example, the kind of values that can be assigned to the property background-color are restricted to <color>, transparent, or inherit. The <color> data type represents a colour in the RGB colour space; the transparent keyword sets the opacity of the background colour to zero; and the inherit keyword tells the browser that the value assigned to background-color is inherited from the current element's parent.

CSS units and value types fall into the following general categories:

Note that length units, whether absolute or relative, consist of a number followed immediately by the unit identifier, with no space in between (if the number is 0, the unit identifier may be omitted).

As well as summarising the CSS units and value types, we will also be taking an in-depth look at the CSS pixel, which is not the same thing as a hardware pixel. In fact, the CSS pixel seems to be the source of some confusion, even among web developers. We will therefore attempt to bring a little clarity to the subject for those of you who are perhaps struggling to get to grips with the relevant section of the W3C specification.

CSS-wide keywords


CSS-wide Keywords
ValueDescriptionApplies to
inherit Represents the computed value of the property on the element's parent. Any CSS property
initial Represents the value specified as the property's initial value. Any CSS property
unset Acts as either inherit or initial, depending on whether the property is inherited or not. Any CSS property

Generic CSS value types


Generic CSS Value Types
Data typeDescriptionApplies to
<color> Represents a colour in the RGB colour space. May include an alpha-channel transparency value, indicating how the colour should composite with its background (see the page "HTML Colours" in the "HTML Basics" section for information on how colours may be specified). background-color
border-bottom-color
border-color
border-left-color
border-right-color
border-top-color
color
outline-color
<integer> Consists of one or several decimal digits, 0 through 9 inclusive, optionally preceded by a single + or - sign. There is no unit associated with integers. order
z-index
<length> Represents a distance value. background-position
border-bottom-width
border-left-width
border-right-width
border-spacing
border-top-width
bottom
font-size
height
left
letter-spacing
line-height
max-height
max-width
min-height
min-width
outline-offset
outline-width
right
text-indent
top
vertical-align
width
word-spacing
<number> Represents a number, being either an integer or a number with a fractional component. flex-grow
flex-shrink
line-height
<percentage> Represents a percentage value. Often used to define a size as relative to an element's parent object. background-position
bottom
font-size
height
left
line-height
max-height
max-width
min-height
min-width
right
text-indent
top
vertical-align
width
<uri> A uniform resource identifier (URI) that can consist of a uniform resource locator (URL) or uniform resource name (URN). The functional notation used to designate URIs in property values is "url()", for example:

    div { background-image: url("background.jpg"); }

Note that URIs may contain a relative or an absolute URL, or a URN that is resolved elsewhere to a relative or an absolute URL.
background-image
list-style-image

Absolute length units


Absolute Length Units
UnitDescriptionEquivalence
cm Centimetre - a unit of length corresponding to one centimetre. 1cm = 96px ÷ 2.54
in Inch - a unit of length corresponding to one inch. 1in = 2.54cm = 96px
mm Millimetre - a unit of length corresponding to one millimetre. 1mm = 0.1cm
pc Pica - a unit of length corresponding to a typographic pica. 1pc ≈ 1/6"
pt Point - a unit of length corresponding to a typographic point. 1pt ≈ 1/72"
px Pixel - a unit of length nominally corresponding to a pixel. 1px = 1/96"

Relative length units


Relative Length Units
UnitDescription
% Percentage values are always relative to another quantity, for example a length. Each property that allows percentages also defines the quantity to which the percentage refers. This quantity can be a value of another property for the same element, the value of a property for an ancestor element, a measurement of the formatting context (e.g., the width of a containing block), or something else.
ch The average character advance (i.e. the horizontal distance from a glyph's origin to the origin of the next glyph on the line, including the white space on both sides) of a narrow glyph in the element's font, as represented by the "0" (ZERO, U+0030) glyph.
em Equal to the font size of the current element. Most user agents have a default base font-size of 16 pixels, so the computed value of 1em is 16 pixels by default. Be aware, however, that because font sizes are inherited, the computed value of 1em will depend on the font size inherited from the parent element.
ex The x-height of the element's font.
rem Equal to the font size of the root element (<html>). Most user agents have a default base font-size of 16 pixels, so the computed value of 1rem is 16 pixels.
vh Equal to 1/100 (1%) of the height of the viewport.
vmax Equal to 1/100 (1%) of the height or width of the viewport, depending on which dimension is larger.
vmin Equal to 1/100 (1%) of the height or width of the viewport, depending on which dimension is smaller.
vw Equal to 1/100 (1%) of the width of the viewport.

CSS property value types


CSS Property Value Types
Data typeDescriptionApplies to
<border-width> Specifies the width of the border area. The <border-width> value type can take one of the following values:
  • thin - a thin border.
  • medium - a medium border.
  • thick - a thick border.
  • <length> - the border width has an explicit value (negative values are not allowed).
The interpretation of the first three values depends on the user agent.
border
border-bottom-width
border-left-width
border-right-width
border-top-width
border-width
outline-width
<border-style> Specifies the line style of a box's border. The <border-style> value type can take one of the following values:
  • none - no border is drawn, and the border width is zero.
  • hidden - same as 'none' (except in terms of border conflict resolution for table elements).
  • dotted - the border is drawn as a series of dots.
  • dashed - the border is drawn as a series of dashes.
  • solid - the border is drawn as a solid line.
  • double - the border is drawn as two parallel solid lines.
  • groove - the border is drawn to simulate a 3d "grooved" look.
  • ridge - the border is drawn to simulate a 3d "ridged" look.
  • inset - the border is drawn to simulate a 3d "sunken" look.
  • outset - the border is drawn to simulate a 3d "raised" look.
Note that, for the 'groove', 'ridge', 'inset' or 'outset' styles to have any effect, the border must have a width of at least two pixels. Similarly, the 'double' style will produce a solid border if the border width is set to less than three pixels. The default width for these styles is (usually) three pixels.
border
border-bottom
border-bottom-style
border-left
border-left-style
border-right
border-right-style
border-style
border-top
border-top-style
outline-style
<margin-width> Specifies the width of the margin area. The <margin-width> value type may take one of the following values:
  • <length> - specifies a fixed width.
  • <percentage> - calculated with respect to the width of the generated box's containing block. If the containing block's width depends on this element, the resulting layout is undefined.
  • auto - centres the element horizontally within its parent container if the width property is set. The element will take up the specified width, and any horizontal space remaining in the parent container will be split equally between the left and right margins.
Negative values for margin properties are allowed, but there may be implementation-specific limits.
margin
margin-bottom
margin-left
margin-right
margin-top
<padding-width> Specifies the width of the padding area. The <padding-width> value type may take one of the following values:
  • <length> - specifies a fixed width.
  • <percentage> - calculated with respect to the width of the generated box's containing block. If the containing block's width depends on this element, the resulting layout is undefined.
Negative values for padding properties are not allowed.
padding
padding-bottom
padding-left
padding-right
padding-top

Other CSS value types


Other CSS Value Types
Value typeDescriptionApplies to
<absolute-size> Represents a keyword that acts as an index into a table of font sizes maintained by the user agent, and can take one of the following values:
  • xx-small
  • x-small
  • small
  • medium
  • large
  • x-large
  • xx-large
font-size
<alphavalue> Represents a value of type <number> that specifies an element's opacity. Values must be in the range 0.0 (fully transparent) to 1.0 (fully opaque). opacity
<family-name> Represents the name of a font family - for example, "Times New Roman", Arial, Times, or Helvetica. Note that non-hyphenated font family names consisting of more than one word must be enclosed within single or double quotes. font-family
<generic-family> Represents the name of a generic font family. The following generic families are defined:
  • serif
  • sans-serif
  • cursive
  • fantasy
  • monospace
font-family
<relative-size> Represents a keyword that is interpreted relative to the table of font sizes maintained by the user agent (see <absolute-size>) and the font size of the parent element; can take one of the following values:
  • larger
  • smaller
Example, if the parent element has a font size of 'medium', a value of 'larger' will set the font size of the current element to 'large'.
font-size

Other CSS keywords


Other CSS Keywords
ValueDescriptionApplies to
100, 200, 300,
400, 500, 600,
700, 800, 900
The values '100' to '900' form an ordered sequence in which each number indicates a weight that is at least as dark as its predecessor. The keyword 'normal' is synonymous with '400', and 'bold' is synonymous with '700'. font-weight
absolute The box's position (and possibly size) is specified with the 'top', 'right', 'bottom', and 'left' properties, which specify offsets with respect to the box's containing block. Absolutely positioned boxes are taken out of the normal flow and have no impact on the layout of later siblings. Their margins do not collapse with any other margins. position
always Always insert a page break (before or after the generated box). page-break-after
page-break-before
armenian Specifies that list item markers will be traditional upper case Armenian numbering. list-style-type
auto A value automatically computed by the user agent. align-self
bottom
flex
height
left
overflow
page-break-after
page-break-before
page-break-inside
right
top
width
z-index
avoid Avoid a page break (before, after or inside the generated box). page-break-after
page-break-before
page-break-inside
baseline Align the baseline of the box with the baseline of the parent box. If the box does not have a baseline, align the bottom margin edge with the parent's baseline. align-items
align-self
vertical-align
blink Text blinks (alternates between visible and invisible). text-decoration
block Causes an element to generates a block-level container. display
bold Text is displayed in a bold font. font-weight
bolder Text is displayed in a font weight that is bolder than that of the parent element. font-weight
border-box Specifies that the width and height of an element are calculated including padding and borders. box-sizing
both Indicates that neither side of an element's box may be adjacent to an earlier floating box. clear
bottom See individual properties for precise meaning. background-position
caption-side
vertical-align
capitalize Puts the first character of each word in upper case. text-transform
caption Indicates that the system font used for captioned controls (e.g., buttons, drop-downs, etc.) is to be used. The font family, size, weight, style, etc. are all set at the same time (these values can be changed individually if required). If a font with the indicated characteristics does not exist on a given platform, the user agent should substitute an appropriate font or a user agent default font. font
center See individual properties for precise meaning. align-content
align-items
align-self
background-position
justify-content
text-align
circle Specifies that the list item marker will be a circle if 'list-style-image' has the value 'none' or if the image pointed to by the URI cannot be displayed. The exact rendering depends on the user agent. list-style-type
collapse See individual properties for precise meaning. border-collapse
visibility
column Indicates that the flex items in a flex container are laid out in a column, and that the main axis runs in the vertical direction. flex-direction
row-reverse Indicates that the flex items in a flex container are laid out in a column, and that the main axis runs in the vertical direction. The order in which the flex items are displayed is reversed. flex-direction
content Indicates an automatic size based on the flex item's content. flex-basis
content-box Specifies that the width and height of an element are calculated excluding padding and borders. box-sizing
dashed A border or outline is drawn using dashes. border-bottom-style
border-left-style
border-right-style
border-style
border-top-style
outline-style
decimal Specifies that list item markers will be decimal numbers, beginning with 1. list-style-type
decimal-leading-zero Specifies that list item markers will be decimal numbers, padded by initial zeros (e.g., 01, 02, 03, ..., 98, 99). list-style-type
disc Specifies that the list item marker will be a disc if 'list-style-image' has the value 'none' or if the image pointed to by the URI cannot be displayed. The exact rendering depends on the user agent. list-style-type
dotted A border or outline is drawn using dots. border-bottom-style
border-left-style
border-right-style
border-style
border-top-style
outline-style
fixed See individual properties for precise meaning. background-attachment
position
flex-end See individual properties for precise meaning. align-content
align-items
align-self
justify-content
flex-start See individual properties for precise meaning. align-content
align-items
align-self
justify-content
georgian Specifies that list item markers will be traditional Georgian numbering (an, ban, gan, ..., he, tan, in, in-an, ...). list-style-type
hidden See individual properties for precise meaning. border-bottom-style
border-left-style
border-right-style
border-style
border-top-style
outline-style
overflow
visibility
icon Indicates that the system font used to label icons is to be used. The font family, size, weight, style, etc. are all set at the same time (these values can be changed individually if required). If a font with the indicated characteristics does not exist on a given platform, the user agent should substitute an appropriate font or a user agent default font. font
inline Causes an element to generates one or more inline container. display
inline-block Causes an element to generate an inline-level block container (the inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box). display
inline-table Causes an element to behave like a table element. display
inside The marker box is placed as the first inline box in the principal block box, before the element's content and before any :before pseudo-elements. list-style-position
invert Performs a colour inversion on the pixels on the screen to ensure that the focus border is visible regardless of the background colour. outline-color
italic Selects a font that is labelled 'italic', or, if that is not available, one labelled 'oblique'. font-style
justify Text is aligned with bot the left-hand and right-hand margins. text-align
left See individual properties for precise meaning. background-position
clear
float
page-break-after
page-break-before
text-align
lighter Text is displayed in a font weight that is lighter than that of the parent element. font-weight
line-through Each line of text has a line through the middle. text-decoration
list-item Causes an element to generate a principal block box and a marker box. display
lower-alpha Specifies that list item markers will be lowercase ascii letters (a, b, c, ... z). list-style-type
lowercase Puts all characters of each word in lower case. text-transform
lower-greek Specifies that list item markers will be lowercase classical Greek alpha, beta, gamma, ... (α, β, γ, ...). list-style-type
lower-latin Specifies that list item markers will be lowercase ascii letters (a, b, c, ... z). list-style-type
lower-roman Specifies that list item markers will be lower case roman numerals (i, ii, iii, iv, v, etc.). list-style-type
menu Indicates that the system font used in menus (e.g., dropdown menus and menu lists) is to be used. The font family, size, weight, style, etc. are all set at the same time (these values can be changed individually if required). If a font with the indicated characteristics does not exist on a given platform, the user agent should substitute an appropriate font or a user agent default font. font
message-box Indicates that the system font used in dialog boxes is to be used. The font family, size, weight, style, etc. are all set at the same time (these values can be changed individually if required). If a font with the indicated characteristics does not exist on a given platform, the user agent should substitute an appropriate font or a user agent default font. font
middle Aligns the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent. vertical-align
no-repeat The background image is not repeated. Only a single copy of the image is displayed. background-repeat
none Usually indicates that the feature associated with a CSS property should not be displayed (see individual properties for precise meaning). background-image
border-bottom-style
border-left-style
border-right-style
border-style
border-top-style
clear
display
flex
float
list-style-image
list-style-type
max-height
max-width
min-height
min-width
outline-style
text-decoration
text-transform
normal See individual properties for precise meaning. font-style
font-variant
font-weight
letter-spacing
line-height
white-space
word-spacing
nowrap See individual properties for precise meaning. white-space
flex-wrap
oblique Selects a font that is labelled 'oblique'. font-style
overline Each line of text has a line above it. text-decoration
outside The marker box is outside the principal block box. list-style-position
pre Prevents user agents from collapsing sequences of white space. Lines are only broken at preserved newline characters. white-space
pre-line Tells user agents to collapse sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes. white-space
pre-wrap Prevents user agents from collapsing sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes. white-space
relative Specifies that the box's position is calculated according to the normal flow (this is called the position in normal flow). Then the box is offset relative to its normal position. When a box B is relatively positioned, the position of the following box is calculated as though B were not offset. The effect of 'position: relative' on table-row-group, table-header-group, table-footer-group, table-row, table-column-group, table-column, table-cell, and table-caption elements is undefined. position
repeat The background image is repeated both horizontally and vertically. background-repeat
repeat-x The background image is repeated horizontally only. background-repeat
repeat-y The background image is repeated vertically only. background-repeat
right See individual properties for precise meaning. background-position
clear
float
page-break-after
page-break-before
text-align
row Indicates that the flex items in a flex container are laid out in a row, and that the main axis runs in the horizontal direction. flex-direction
row-reverse Indicates that the flex items in a flex container are laid out in a row, and that the main axis runs in the horizontal direction. The order in which the flex items are displayed is reversed. flex-direction
scroll See individual properties for precise meaning. background-attachment
overflow
separate Selects the separated borders border model for 'table' and 'inline-table' elements. border-collapse
small-caps All lowercase letters are converted to uppercase letters, but using a smaller font size and with slightly different proportions. font-variant
small-caption Indicates that the system font used for labelling small controls is to be used. The font family, size, weight, style, etc. are all set at the same time (these values can be changed individually if required). If a font with the indicated characteristics does not exist on a given platform, the user agent should substitute an appropriate font or a user agent default font. font
space-around See individual properties for precise meaning. align-content
justify-content
space-between See individual properties for precise meaning. align-content
justify-content
square Specifies that the list item marker will be a square if 'list-style-image' has the value 'none' or if the image pointed to by the URI cannot be displayed. The exact rendering depends on the user agent.
static Specifies that the box is a normal box, laid out according to the normal flow. The 'top', 'right', 'bottom', and 'left' properties do not apply. position
status-bar Indicates that the system font used in window status bars is to be used. The font family, size, weight, style, etc. are all set at the same time (these values can be changed individually if required). If a font with the indicated characteristics does not exist on a given platform, the user agent should substitute an appropriate font or a user agent default font. font
stretch See individual properties for precise meaning. align-content
align-items
align-self
sub Lowers the baseline of the box to the proper position for subscripts of the parent's box (has no effect on font size). vertical-align
super Raises the baseline of the box to the proper position for superscripts of the parent's box (has no effect on font size). vertical-align
table,
table-caption,
table-cell,
table-column,
table-column-group,
table-footer-group,
table-header-group,
table-row,
table-row-group
Causes an element to behave like a table element. display
text-bottom Aligns the bottom of the box with the bottom of the parent's content area. vertical-align
text-top Aligns the top of the box with the top of the parent's content area. vertical-align
top See individual properties for precise meaning. background-position
caption-side
vertical-align
transparent Sets the background or foreground colour of an element to transparent, making the background behind the coloured item completely visible. background-color
border-bottom-color
border-color
border-left-color
border-right-color
border-top-color
underline Each line of text is underlined. text-decoration
upper-alpha Specifies that list item markers will be upper case ascii letters (A, B, C, ... Z). list-style-type
uppercase Puts all characters of each word in upper case. text-transform
upper-latin Specifies that list item markers will be upper case ascii letters (A, B, C, ... Z). list-style-type
upper-roman Specifies that list item markers will be upper case roman numerals (I, II, III, IV, V, etc.). list-style-type
visible See individual properties for precise meaning. overflow
visibility
wrap Indicates that a flex container is multi-line. flex-wrap
wrap-reverse Indicates that a flex container is multi-line, with line order reversed. flex-wrap

The CSS pixel

You'll often see devices like televisions, computer screens, tablets, and smartphones described as "Full HD" or "1080p". In the case of a TV or computer monitor it means that they have a vertical resolution of 1,080 pixels. And, since these devices usually have a widescreen aspect ratio of 16:9, they will also have a horizontal resolution of 1,920 pixels.

A full HD smartphone or tablet has the same resolution overall, but will normally be viewed in portrait mode, giving a vertical resolution of 1,920 pixels, a horizontal resolution of 1,080pixels, and an aspect ratio (in portrait mode) of 9:16. In essence, all of these devices will have the same number of screen pixels (we'll call them device pixels), which is 1,080 × 1,920 = 2,073,600 pixels.

Having said that, they range in size from quite small (smartphones and tablets) to very large (1080p TV sets), with most desktop computers and laptops having screens that fall somewhere in between. If we want our web pages to be displayed optimally on all of these devices, we need to understand a few things about CSS pixels, which are not the same thing as device pixels.

The W3C specification seems to tell us quite categorically that a CSS pixel is 1/96th of an inch. Here is a partial screen shot taken from section 6.2 of the CSS Values and Units Module Level 4 W3C Working Draft, 31 January 2019, which provides the source information for the table "Absolute Length Units" (see above):


The CSS absolute length units as defined by W3C

The CSS absolute length units as defined by W3C


There are several things to note here. First of all, the cm (centimetre) and in (inch) units are both defined in terms of the px (pixel) unit, while all other units (including the px unit) are defined either in terms of the inch or the centimetre. Second, the word "equivalence" is used, which implies that the units are interchangeable, and that we can convert dimensions from one unit to another.

The first sign that all is not quite what it seems, however, is the phrase that immediately precedes the table:

"The absolute units consist of the physical units (in, cm, mm, pt, pc, Q) and the visual angle/pixel unit (px):"

What is the "visual angle", and how does it relate to a pixel density of 96 pixels per inch? For many years, desktop computers with CRT monitors were the primary means of accessing the World Wide Web, and these monitors typically had a pixel density of (circa) 96 pixels per inch.

At the time of writing, desktop computer monitors vary from about 21.5 inches to 28 inches, with 24 inches being a popular (and reasonably affordable) choice. Most of these screens have a full HD resolution of 1920 × 1080 pixels, and pixel densities ranging from just under 80 ppi for a 28-inch screen to about 102 ppi for a 21.5-inch screen. A 24-inch screen would have a pixel density of approximately 92 ppi.

So, in some ways, not much has changed. What has changed is the fact that we now have a very diverse range of options when it comes to accessing online content, including smartphones, tablets, Internet-enabled televisions, netbooks, laptops, and of course the desktop computer. Screen resolutions can vary considerably, as can the physical size of the display screen.

The assumption of an average device pixel density of 96 ppi is not unreasonable when it comes to desktop computer monitors, but it no longer applies when we start looking at display devices that are physically much smaller (or conversely, much bigger), even though they may have the same number of pixels.

Mobile devices like a smartphones and tablets are much smaller than their desktop counterparts, and must have a much higher pixel density in order to achieve the same or comparable screen resolutions. This has the potential to make our content harder to read, which is where the "visual angle" comes in. W3C's current specification defines what it calls a "reference pixel":

"The reference pixel is the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm's length. For a nominal arm's length of 28 inches, the visual angle is therefore about 0.0213 degrees. For reading at arm's length, 1px thus corresponds to about 0.26 mm (1/96 inch)."

Let's consider first of all how this will impact on the way in which a web page is rendered on a typical desktop computer display device, like the one illustrated below.


A typical HD computer monitor

A typical HD computer monitor


The typical HD computer monitor shown above has a vertical resolution of 1080 device pixels and a horizontal resolution of 1920 device pixels, resulting in a device pixel density of circa 93.4 pixels per inch (ppi) - very close to the nominal 96 pixels-per-inch specified by W3C. One CSS pixel will therefore be mapped to one device pixel.

According to W3C, 'px' is the canonical unit for absolute length units in CSS (i.e. the unit used to determine the value of other, related units). This means that if we assume a one-to-one relationship between device pixels and CSS pixels, and if the device pixel is not exactly 1/96" (as is the case in the example above), then other CSS absolute units (inches, centimetres etc.) will also differ slightly from their real-world counterparts. For example, consider the following CSS rule:

div.comment_box {
  border: solid 1px red;
  margin: 0 auto;
  width: 3in;
}

Let's suppose our page is rendered on an HD computer monitor with dimensions identical to those shown in the illustration. The physical dimensions of the <div> element on screen would be based on the CSS inch unit, which has a value of 96 CSS pixels. Because the monitor has a pixel density of 93.4 ppi - slightly less than the 96 ppi assumed by CSS - the actual width of the <div> element on screen can be found using the following calculation:

3 × 96px ÷ 93.4   =   288px ÷ 93.4   =   3.0835"

So, a CSS "inch" doesn't necessarily match the physical measurement that its name implies, which seems to contradict the W3C specification. However, when you consider the sheer diversity of display devices, in terms of both their physical size and the resolutions they offer, this is hardly surprising. The W3C specification has this to say:

"For a CSS device, these dimensions are anchored either

    i. by relating the physical units to their physical measurements, or
    ii. by relating the pixel unit to the reference pixel.

For print media at typical viewing distances, the anchor unit should be one of the physical units (inches, centimeters, etc). For screen media (including high-resolution devices, low-resolution devices, and devices with unusual viewing distances), it is recommended instead that the anchor unit be the pixel unit. For such devices it is recommended that the pixel unit refer to the whole number of device pixels that best approximates the reference pixel.

Note: If the anchor unit is the pixel unit, the physical units might not match their physical measurements. Alternatively if the anchor unit is a physical unit, the pixel unit might not map to a whole number of device pixels."

In other words, physical units like centimetres and inches are only really meaningful in the context of printed media. When it comes to screen media we need to think in terms of pixels. And because the physical size of a screen pixel will vary considerably from one display device to another, we need to see the CSS pixel as an abstract unit based on visual perception rather than as a physical unit.

As we have seen, W3C defines the reference pixel as "the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of . . . a nominal arm's length of 28 inches". An object's visual angle is the angle subtended by the light from the object (in this case a single pixel) as it enters the eye of an observer. The diagram below illustrates the principle.


Pixels must become large as distance increases to maintain the same visual angle

Pixels must become large as distance increases to maintain the same visual angle
Image: CSS Values and Units Module Level 4 - W3C Working Draft, 31 January 2019


As you can see from the diagram, the further away a pixel is from the observer, the larger it has to be to cover the same visual angle, which is why a HD television is typically much larger than a HD computer display screen despite having exactly the same vertical and horizontal resolution and the same aspect ratio. It is designed to be viewed from further away, and consequently has a much larger pixel size.

The illustration below demonstrates how this works. It shows a desktop display screen in the background, some distance away from us, and a smartphone in the foreground. Both devices are displaying a box in the centre of the screen. The square on the desktop screen is actually physically much bigger than the square on the smartphone screen, but we perceive them as being the same size because the smartphone is closer to us.


We perceive the square to be the same size on both devices

We perceive the square to be the same size on both devices


The dimensions of the box in CSS pixels will be the same, but whereas a CSS pixel on the desktop display equates to a single device pixel, the CSS pixel on the smartphone will typically equate to three or four pixels, or even in some cases a fractional number of device pixels, depending on the make and model. If we assume a device pixel ratio of three, a typical 1080p smartphone display would have a resolution of 360 × 640 pixels (in CSS pixels).

We are particularly interested in smartphones, because the number of people surfing the web on their smartphone is set to overtake the number of people using desktop computers or laptops for the same purpose. Indeed, according to some sources that may already be the case. It is therefore very important for web developers to understand how their pages will be rendered on these devices. The trick is to ensure that our content is as easy to read on these devices as it is on a desktop display.

A typical smartphone these days has a diagonal display screen dimension of between five and six inches. Let's assume, then, an average of five-and-a-half inches, and an aspect ratio of 9:16. This would result in a device with display screen dimensions of (circa) 2.7 x 4.8 inches, as illustrated below.


A generic 5.5

A generic 5.5" smartphone


Various studies have been carried out to determine how far people hold their phone from their eyes. The results of one such study, published online in 2011 by the Journal of the American Academy of Optometry, "Font Size and Viewing Distance of Handheld Smart Phones", suggests that distances ranged from 17.5 to 58 centimetres (6.88 to 22.83 inches) for reading text messages, and from 19 to 60 centimetre (7.48 to 23.63 inches) for Internet viewing. The mean working distance was found to be 36.2 centimetres (14.25 inches) for reading text messages, and 32.2 centimetres (12.68 inches) for Internet viewing.

Viewing distances will vary from one person to the next due to factors such as age and visual acuity. And, although smartphone usage is now so common that we tend to take it for granted, it is still a relatively new phenomenon, and one centred on a rapidly evolving technology. It may be some time, therefore, until sufficient research has been done to determine the optimum viewing distance for these devices, both in terms of usability and in order to avoid damage to our eyesight.

Trying to second guess the result of any such research is probably a fruitless exercise. Web developers must therefore rely to some extent on decisions made by hardware manufacturers and mobile operating system vendors to ensure that their pages are optimally displayed. For example, the default font size for most web browsers is 16px. On a typical desktop computer, this produces text that most people with reasonably good eyesight can read without straining their eyes. How will the same text look on a typical smartphone?

If the text were to be rendered on a smartphone using device pixels it would be much more difficult to read. Even assuming an average viewing distance of 14 inches - half the distance suggested by W3C for display devices with a pixel density of 96 ppi - the pixel density of a typical smartphone screen is far greater, typically in the order of 400+ ppi.

If a pixel at a viewing distance of 28 inches measures 0.26mm, then in order to maintain the same visual angle, a pixel at a distance of 14 inches should measure 0.13 mm. Our generic 5.5" smartphone has a pixel density of 400 pixels per inch - a pixel size of 0.0635 mm (0.0025"). This is less than half the size it needs to be in order to maintain the visual angle defined for a CSS reference pixel. Thanks to a concept pioneered by Apple with their Retina display devices, however, hardware manufacturers now differentiate between hardware pixels and software pixels.

For any given device, the hardware manufacturer will determine the number of hardware pixels that equal one software pixel - a relationship known as the device pixel ratio. Apple's early Retina devices had a device pixel ratio of two, which meant that each software pixel consisted of a 2×2 grid of device pixels. Samsung were the first manufacturer to introduce a device pixel ratio of three (a 3×3 grid), and LG was the first manufacture to use a 4×4 grid.

You don't have to do a lot of research or maths to find out what device pixel ratio your desktop computer, laptop, tablet or smartphone has. Just go to the website www.mydevice.io, and you will immediately see a comprehensive summary of screen metrics relating to your device, including the display size (in CSS pixels), the device pixel ratio, and the pixel density in ppi*. The following screenshots were taken from a Samsung Galaxy A5 (2017) smartphone:


A summary of screen metrics including screen size in CSS pixels . . .

A summary of screen metrics including screen size in CSS pixels . . .



. . . and screen density

. . . and screen density


* The resolution of 288.00 dpi reported is based on a CSS inch, which is anchored to the CSS reference pixel. The software can't calculate the actual device pixel density because there is no way for it to determine the screen's actual physical dimensions. According to Samsung, the Galaxy A5 (2017) has a 5.2" screen and an aspect ratio of 16:9, which translates to screen dimensions of circa 2.55 × 4.53 inches and a pixel density of between 423 and 424 ppi (Samsung give a figure of ~424 ppi).

We sometimes use media queries (we'll be discussing these in details elsewhere), to specify that different CSS rules should be applied to our web page depending on the size of the viewport or the screen resolution (in pixels) of the device on which they are to be displayed. The pixels in question are CSS pixels (software pixels). When we specify a value for a length dimension, like the width of a container or a font size, the size is calculated using CSS pixels.

For example, suppose we want to display some text at twice the standard font size. We might use the following CSS rule:

p.special { font-size: 2em; }

If we assume that 1em represents a default font size of 16 pixels, then the text inside a paragraph element of class .special will have a font size of 32 pixels. But, since we have a device pixel ratio of three, the font size in device pixels will be 32 × 3 device pixels, or 96 device pixels. Bearing in mind that the CSS pixel is the canonical unit for all of the absolute size units in CSS, what implications will this have for CSS units like inches or centimetres?

On a device that has a pixel density of exactly 96 ppi and a device pixel ratio of one, then one CSS pixel will represent exactly one device pixel, one CSS inch will equate to one physical inch, and one CSS centimetre will equal one physical centimetre. In fact, for any display device with a ppi of 96n and a device pixel ratio of n, a CSS pixel will represent exactly n device pixels and all other CSS absolute length units will match their real-world counterparts.

It probably goes without saying that this is rarely the case. Desktop computer display screens often have a pixel density that is close to 96 ppi, although as we have seen, this figure can vary considerably depending on the physical dimensions and screen resolution of the display device. Even so, there is usually a one-to-one correlation between device pixels and CSS pixels for desktop displays.

Full HD mobile devices have a far greater pixel density. As we saw above, the W3C recommendation for such devices is that the CSS pixel should be interpreted as the integer number of device pixels that most closely approximates the reference pixel. The number of device pixels chosen to represent a single CSS pixel will thus depend on the physical size of the screen, the device pixel density, and the estimated optimum viewing distance.