CSS Units
CSS units are the metrics used to define the values of HTML element properties like width, height, margins, padding, or font-size. For example, if you have an <h1> tag, units are what you use to dictate the width of the tag, its font-size, and margins. Ultimately, units are the tools used to define the sizes of things on the webpage.
CSS units are important for the sake of responsiveness and accessibility. In modern web development, websites must be developed in ways that make them presentable on different screen sizes. The tools that are ultimately used to enable websites to be responsive are CSS units.
These units are divided into two categories based on their responsiveness: Absolute Units and Relative Units.
Absolute Units
Absolute units are fixed. This means the absolute unit is not responsive to the changing or different screen sizes the website will appear on. These types of units are mostly used for styling elements that do not need to change according to some external factor. Examples are borders, border-radius, and dropdown shadows of an HTML element. Some absolute units are pixels (px) and points (pt).
Relative Units
Relative units are opposites of absolute units. Relative units are flexible and change according to external factors like the parent container. For example, if the width of a red container is 50% of the width of its parent container, then the width of that red container will expand or contract according to the size of its parent. Some relative units are rem, em, percentage (%), and viewport width or height.
Types of Units
| Unit | Type | Explanation |
|---|---|---|
| px (Pixels) | Absolute | A reference unit that the browser maps to physical pixels depending on the screen's pixel density. On high-density (e.g. Retina) displays, one CSS pixel may correspond to multiple physical pixels. It is the most common unit for precise control. |
| em | Relative | Based on the font size of the parent element. |
| rem | Relative | Stands for "root em." Based on the font size of the root (<html>) element rather than the parent. |
| % (Percentage) | Relative | Relative to the size of the parent container. |
| vw / vh | Relative | 1% of the viewport's width or height, respectively. |
| vmin / vmax | Relative | Based on the smaller (min) or larger (max) dimension of the viewport. |
| ch | Relative | Based on the width of the "0" (zero) character of the element's font. |
| cm / in / pt | Absolute | Standard physical measurements (centimeters, inches, points). |
Note: While units like cm or in exist, they are primarily intended for print stylesheets and do not translate accurately to digital screen displays.