Article
The Ultimate Guide to CSS Units
Ever wondered how websites magically fit on screens of all sizes? Or how can you adjust your text size if someone zooms in? The secret lies in mastering CSS units. In this guide, we'll demystify units and help you choose the right ones to build stunning, adaptable layouts.
Absolute Units – The Fixed Sizes
Let's start with absolute units. They have a fixed size, regardless of screen or other elements. The most common one is the pixel (px), but there are others like inches (in), centimeters (cm), and points (pt).
- Pros: Easy to grasp and ideal for print stylesheets where physical size matters.
- Cons: Inflexible for varied screen sizes. Using too many absolute units can make your website look awkward on smaller or larger displays.
- rem: Relative to the current element's font size.
- Why They're Awesome: These help you build responsive websites, ensuring your content looks great on any device. They're also good for accessibility!
- CSS
- p {
- font-size: 1.2rem; /* 20% larger than the base font size */
- }
- CSS
- .sidebar {
- max-width: 30%; /* Takes up a maximum of 30% of its parent container */
- }
- Pixels (px): Precision work (thin borders, fixed-size icons)
- Percentages (%): Flexible layouts (e.g., making columns take up a certain percentage of their container).
- rem: Global scaling (base font size, consistent margins throughout your site).
- Viewport units (vw, vh): Elements that relate to the screen size (full-screen sections, large headings that scale with the window).
- Watch Out! Be careful with nesting relative units like them within them. It can lead to unexpectedly large or tiny elements.
- Responsive Layout Recipe:
- CSS
- .container {
- max-width: 90%;
- margin: 0 auto;
- }
- .column {
- width: 30%;
- float: left;
- margin: 1rem;
- }
- This, along with some media queries, builds a basic multi-column layout.
- User-Friendly Text: Use relative font sizes (em or rem) to allow people with visual impairments to zoom in on your text more easily.
- px: Fixed sizes
- em: Relative to the current font size
- rem: Relative to the root font size
- %: Relative to the parent element
- vw/vh: Relative to the viewport width/height