Values and Units in CSS
There are many types of values for CSS properties: numeric values, colors, functions that perform a certain action, and others. Sometimes, to specify exact values, we need to use various units of measurement.
We will explore values such as length, color, and simple functions, as well as less common values, such as degrees and even unitless values.
- Numeric values
- Percentages
- Colors
- Functions
Numeric Values
These are frequently used in CSS.
Length and Size
You will constantly use length and size units in CSS, for layout, typography, and much more.
In the example above, we applied a top and bottom margin of 10px, and for the left and right
margins we used the value auto, which centered the paragraphs horizontally. We also applied
10px for padding (inner space of paragraphs) and 2px for border
using shorthand notation. A single value for margin and padding applies the same value
to all four sides.
We set width to increasingly larger sizes, and the text “boxes” grow accordingly. Similarly,
font-size increases from top to bottom. Font size refers to the height of each glyph.
Pixels (px) are absolute units, because they maintain the same size regardless of other settings.
Other absolute units are: q (1/40 of a cm), mm, cm, in
(2.54 cm), pt (1/72 of an inch), pc (12pt). Of these, px is the most
used.
There are also relative units based on font size or viewport size:
- em – 1em represents the font size of the current element (default 16px in most browsers). Note: font sizes are inherited, and em values for nested elements are calculated relative to the direct parent.
Notice how the font size increases from one paragraph to another:
- ex, ch –
exis relative to the height of the lowercase “x” in the current font, andchis relative to the width of the “0” (zero) in the current font. Both are rarely used. - rem (root em) – works exactly like em, except it is always equal to
the computed font size of the root element (
html) and inherited sizes have no effect. When specifyingfont-sizein rem for the root element, it refers to the initial default value.
→ 1rem = font size of thehtmlelement (in most browsers 16px).
Therefore, rem is often a better option than em, but it does not work well in older versions of Internet Explorer.
Main issue: rem values may be less intuitive for calculations. Examples, starting from a base of 16px:
- 10px = 0.625rem
- 12px = 0.75rem
- 14px = 0.875rem
- 16px = 1rem (base)
- 18px = 1.125rem
- 20px = 1.25rem
- 24px = 1.5rem
- 30px = 1.875rem
- 32px = 2rem
As you can see, values are not always convenient for quick calculations. Fortunately, there is an old trick also used for em: setting the base font to 62.5% – which makes 1em or 1rem equal to 10px.
body { font-size: 62.5%; } /* =10px */
h1 { font-size: 2.4em; } /* =24px */
p { font-size: 1.4em; } /* =14px */
li { font-size: 1.4em; } /* =14px */
The equivalent for rem is:
html { font-size: 62.5%; } /* =10px */
body { font-size: 1.4rem; } /* =14px */
h1 { font-size: 2.4rem; } /* =24px */
To cover older browsers that do not recognize the rem unit, we can use a combined syntax:
html {
font-size: 62.5%;
}
body {
font-size: 14px; /* fallback */
font-size: 1.4rem; /* modern */
}
h1 {
font-size: 24px; /* fallback */
font-size: 2.4rem; /* modern */
}
There are numerous articles and discussions online about this topic, pros and cons.
- vw, vh –
vwrepresents 1/100 of the viewport width, so100vwcovers the entire width of the viewport.vhrepresents 1/100 of the viewport height, and100vhequals the full height. They are useful in certain situations and are not affected by inheritance, but support in all browsers is not yet perfect, so they should be used with caution after testing. - vmin, vmax –
vminis relative to the smaller dimension of the viewport. If height is less than width, 1vmin = 1% of height; conversely, if width is smaller, 1vmin = 1% of width. vmax is relative to the larger dimension of the viewport: if height exceeds width, 1vmax = 1% of height, and if width is larger, 1vmax = 1% of width.
Hypothetical examples:
➤ Screen: 1200px width × 1000px height → 10vw = 120px, 10vh = 100px. Width is larger → 10vmax = 120px, 10vmin = 100px.
➤ Screen rotation: 1000px width × 1200px height → 10vh = 120px, 10vw = 100px. 10vmax remains 120px (now height dictates), 10vmin remains 100px.
➤ Window resize: 1000px width × 800px height → 10vh = 80px, 10vw = 100px, 10vmax = 100px, 10vmin = 80px.
Viewport units seem similar to percentages (which we will discuss next), but they are different: with percentages, the size of the child element is relative to its parent.
As you could see in the example above, the width of the first child element is set to 80% of its parent's width. However, the second child element has a width of 80vw, which makes it wider than its parent.
Since these units are based on viewport dimensions, it is very convenient to use them when the width, height, or size of elements needs to be set relative to the display.
- values without units - these are allowed in certain circumstances. For example, if you want to completely remove margin and padding from an element, you can use the value "0" (zero), regardless of previous settings:
margin: 0; padding: 0;
Another example involves text line height (line-height). You can use units to set a specific line height, but often it is easier to use a unitless value, which acts as a simple multiplier:
In the example above, the font size is 16px, and the line height will be 1.5 times larger, i.e., 24px (16*1.5).
- percentage units can be used to specify almost any values for properties that accept numeric values. This allows us to create elements whose sizes change by a certain percentage of the parent container's size. This is not possible when using px or em.
As you could observe, the container with a width defined in px keeps its size even when the window is resized.
These two different types of container layouts are often called liquid layout (changes with the viewport) and fixed width layout (keeps its dimensions). They have different uses:
- The fluid (liquid) layout can be used to ensure that a document always fits the display (screen) and looks good regardless of the display size,
- The fixed width layout could be used to display a map that always has the same size, but only a certain portion is visible. To see another part of the map, you need to use the scroll bars of the browser window, and the visible portion will depend on the size of the display device used for viewing.
- number of animations - in this case, a simple integer number is used as a unit of measure. Animations allow you to animate different HTML elements on the page.
In the example above, several units of measure are used. We are interested in the property animation-iteration-count: 5;, to highlight the use of the value 5, which is an integer and implies repeating the animation 5 times.
Colors
There are many ways to specify colors in CSS. The same color values can be used anywhere in CSS, whether you are specifying text color, background color, or anything else. The standard color system available on modern computers is 24-bit, which allows displaying about 16.7 million distinct colors by combining the different red, green, and blue channels, with 256 values for each channel (256x256x256=16,777,216).
☞ To convert between the different color systems we are going to discuss, you will need a color converter. There are many such online tools, but you can also use the converter below.
Specifying color using its name
The simplest and oldest method is to specify a color using its name.
p {
background-color: red;
}
This method is easy to understand but drastically limits our options, because there are only about 165 color names available in modern browsers.
Hexadecimal Color System
The next ubiquitous color system is represented by hexadecimal codes (or hex) and is somewhat harder to understand but much more versatile, being widely used. Each value consists of a # symbol, followed by six digits, each of which can take a value from 0 to f (0123456789abcdef).
Each pair of values represents one of the channels – red, green, and blue – and allows specifying any value among the 256 available for each (16 x 16 = 256).
☞ The hexadecimal system is the base-16 numeral system, usually written using the symbols 0-9 and A-F. The system is more common in computing, where it is used extensively because one byte exactly contains two hexadecimal digits.
RGB Color System
This system is very well supported by almost all browsers and widely used in CSS. RGB stands for Red, Green, Blue. Unlike the hexadecimal system, each of these colors can take any value between 0 and 255.
HSL Color System
HSL stands for hue, saturation, and lightness – this allows representations of over 16 million colors, but in a different way.
- Hue – the base hue of the color expressed in degrees, with values between 0 and 360. On a color wheel, around 0 we find red, at 60° yellow, at 120° green, at 180° cyan, at 240° blue, at 300° violet (purplish red), and at 360° red again.
- Saturation – percentage values from 0-100%, where 0 has practically no color (a weak gray shade) and 100% has full saturation.
- Lightness – indicates how light or bright a color is, expressed as a percentage from 0-100%, where 0 is no light (black) and 100% is full light (white).
As can be seen, the HSL system appears much more intuitive than other systems, and now that it is much better supported by browsers than a few years ago, I anticipate it will soon become the preferred system for designers.
For example, it is simple and easy to identify a set of hues that blend in a monochromatic color scheme.
/* three different shades of red */ background-color: hsl(0,100%,50%); background-color: hsl(0,100%,60%); background-color: hsl(0,100%,70%);
Modern color spaces: CSS Color Module Level 4 and 5 introduce new color spaces such as
lab(), lch(), oklab(), and oklch(), which provide more
precise and consistent color reproduction across devices. These are useful for accessible designs and for
maintaining color consistency in print and on screens.
Example:
/* red in LCH space */ background-color: lch(54.29 106.84 40.85); /* violet in OKLCH space */ background-color: oklch(62.2345% 0.2779 328.21);
Additionally, the color-mix() function allows mixing two colors directly in CSS:
background-color: color-mix(in lch, red 40%, blue);
RGBA and HSLA
The "A" at the end of RGB and HSL stands for the alpha channel, responsible for the opacity of the object's color. For the alpha channel, we can specify a number between 0 (completely transparent) and 1 (completely opaque).
Opacity
There is another way to specify transparency in CSS – the "opacity" property. Using this property, you can modify the transparency of all selected elements as well as their children.
Color transparency: The background-color property now accepts alpha channel
notation directly in hex (#RRGGBBAA), for example #ff000080 for red with 50% opacity.
This is shorter and easier to read in some contexts.
Functions
In programming, a function is a reusable code snippet that can be run multiple times to perform a repetitive task with minimal effort from both the author and the computer.
CSS also has functions, even though it is not a programming language. We have already seen various functions in action in the color section – rgb(), hsla(), functions that calculate which colors will be displayed in the browser.
In general, whenever you see a value followed by parentheses containing other values separated by commas, you are dealing with a function.
/* calculates the position of an element after it has been rotated 45 degrees */
transform: rotate(45deg);
/* calculates the new position of an element after moving left by 50px and down by 60px */
transform: translate(50px, 60px);
/* sets the calculated value of 90% of the current width minus 15px */
width: calc(90% - 15px);
/* finds and loads a background image in the document */
background-image: url('image.png');
/* creates a color gradient for the background */
background-image: linear-gradient(to left, teal, aquamarine);
New CSS functions (Level 4 and 5): Functions like min(), max(),
clamp() for flexible limits, round() and mod() for mathematical
calculations, trigonometric functions (sin(), cos(), tan()),
hypot() for calculating the hypotenuse, as well as random() and
random-item() (experimental) for generating random values have been added. The attr()
function can now be used in any CSS property, with data types and default values.
