What Are CSS Units: Simple Explanation and Examples
px (pixels) and relative units like em or rem, which scale based on other elements or the viewport.How It Works
Think of CSS units like the rulers or measuring tapes you use in real life to decide how big or small something should be. When you style a webpage, you need to tell the browser how large or small elements should appear. CSS units give you a way to do this by specifying lengths in different ways.
There are two main types of CSS units: absolute and relative. Absolute units, like pixels (px), are fixed sizes, similar to using a ruler with fixed inches or centimeters. Relative units, like em or rem, change size depending on other things, like the size of the text around them or the size of the screen. This is like using a stretchy tape measure that adjusts based on the size of the room.
Example
This example shows a box with a fixed width using pixels and a font size using relative units. The box width stays the same, but the text size can adjust if the base font size changes.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Units Example</title> <style> .box { width: 200px; /* fixed size */ border: 2px solid #333; padding: 1rem; /* relative to root font size */ font-size: 1.5rem; /* 1.5 times root font size */ } </style> </head> <body> <div class="box">This box is 200 pixels wide with text sized using rem units.</div> </body> </html>
When to Use
Use absolute units like px when you want precise control over element sizes, such as borders or icons that should not change size. Use relative units like em or rem for text sizes and spacing to make your design flexible and accessible. This helps your webpage look good on different screen sizes and respects user preferences like zoom or font size settings.
For example, use rem for font sizes so text scales consistently across the page, and use percentages or viewport units (vw, vh) for layouts that adapt to screen size.
Key Points
- CSS units measure sizes for styling elements on a webpage.
- Absolute units like
pxare fixed and do not change with screen size. - Relative units like
em,rem, and%scale based on other elements or viewport. - Using relative units improves accessibility and responsiveness.
- Choose units based on whether you want fixed or flexible sizing.