CSS units define the size of elements in your webpage. They are classified into two main categories: absolute and relative units. Let’s break them down!
These units have a fixed size that does not change, regardless of the viewport or parent elements.
px (Pixels):
Most commonly used. One px is a fixed unit based on the resolution of the device.
font-size: 16px; /* Fixed size of 16 pixels */
cm (Centimeters) & mm (Millimeters):
Rarely used, primarily for print design.
width: 10cm; /* Width of 10 centimeters */
in (Inches):
Also used for print media; 1 inch equals 96 pixels.
width: 1in; /* Width of 1 inch */
Absolute units are best for print layouts or when you need precise, unchanging sizes. However, they are not ideal for responsive designs.
These units are dynamic and scale based on their environment, such as the parent element or the viewport.
% (Percentage):
Relative to the size of the parent container.
width: 50%; /* Takes 50% of the parent's width */
em:
Relative to the font size of the parent element.
padding: 1.5em; /* 1.5 times the parent font size */
rem (Root EM):
Relative to the font size of the root element (<html>), typically 16px by default.
font-size: 2rem; /* 2 times the root font size (e.g., 16px * 2 = 32px) */