CSS Units of Measurement
A web page, as you know, is two-dimensional with width and height, often described in terms like vertical and horizontal, length and breadth, or the X and Y axes. Another key aspect of a webpage is its size, which can be either static or dynamic. As you dive deeper into CSS, you’ll encounter different units of measurement used to define the size of elements, each suited to different scenarios, especially when considering the variety of devices and screen sizes.
Absolute Units
Absolute units are fixed in size and remain constant across devices, making them ideal for print-based layouts where exact measurements are needed. However, in the context of web pages, where device screen sizes vary, absolute units are not as commonly used for responsive designs.
Here’s a table of commonly used absolute units:
Unit | Name | Comparison |
---|---|---|
Q | Quarter-millimeters | 1Q = 1/40th of 1cm |
mm | Millimeters | 1mm = 1/10th of 1cm |
cm | Centimeters | 1cm = 37.8px = 25.2/64in |
in | Inches | 1in = 2.54cm = 96px |
pc | Picas | 1pc = 1/6th of 1in |
pt | Points | 1pt = 1/72nd of 1in |
px | Pixels | 1px = 1/96th of 1in |
Among these, pixels and centimeters are the most frequently used for defining element sizes.
Relative Units
Relative units are defined in relation to other elements, the parent element, or the viewport size. Given the dynamic nature of modern web design, relative units are preferred because they adapt to different screen sizes and element relationships.
Here’s a table of common relative units:
Unit | Description and Relativity |
---|---|
em | Relative to the font size of the parent element. |
ex | Relative to the height of the font (x-height). |
ch | Relative to the width of the "0" (zero) character. |
rem | Relative to the font size of the root element (<html> ). |
lh | Relative to the line height of the parent element. |
rlh | Relative to the line height of the root element (<html> ). |
vw | 1% of the viewport width. |
vh | 1% of the viewport height. |
vmin | 1% of the smaller dimension of the viewport. |
vmax | 1% of the larger dimension of the viewport. |
% | Denotes a percentage value relative to the parent element. |
Relative units like vw
, vh
, and percentages are commonly used when dealing with responsive designs and variable viewport sizes. em
, rem
, and vh
are often used to control font sizes and layout in a flexible way.
Conclusion
Different CSS properties may require different units, depending on their context. For example, color properties like background-color
can be expressed in values like hexadecimal, rgb()
, rgba()
, hsl()
, or hsla()
. Experimenting with various units of measurement and understanding their behavior in different scenarios will help you determine the best unit to use in your designs.