Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
CSS Relative units
CSS relative units are units whose values are relative to another measurement. Unlike absolute units, relative units scale based on their context, making them ideal for responsive design. The size of elements using relative units will adapt based on their parent element or viewport size.
Syntax
selector {
property: value unit;
}
Common Relative Units
| Unit | Abbreviation | Description |
|---|---|---|
| Percent | % | Relative to the parent element |
| Em | em | Relative to the font-size of the element |
| Root em | rem | Relative to the font-size of the root element |
| Ex | ex | Relative to the x-height of the font |
| Character | ch | Relative to the width of the "0" character |
| Viewport width | vw | 1% of the viewport width |
| Viewport height | vh | 1% of the viewport height |
Example: Using Percentage Units
The following example demonstrates how percentage units work relative to the parent container −
<!DOCTYPE html>
<html>
<head>
<style>
.parent {
width: 400px;
height: 200px;
background-color: #f0f0f0;
border: 2px solid #333;
}
.child {
width: 50%;
height: 75%;
background-color: #4CAF50;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">50% × 75%</div>
</div>
</body>
</html>
A gray parent container (400px × 200px) with a green child element that is 200px wide (50% of 400px) and 150px tall (75% of 200px).
Example: Using Em and Rem Units
This example shows the difference between em and rem units for font sizing −
<!DOCTYPE html>
<html>
<head>
<style>
html {
font-size: 16px; /* Root font size */
}
.container {
font-size: 20px;
padding: 20px;
border: 1px solid #ccc;
}
.em-text {
font-size: 1.5em; /* 1.5 × 20px = 30px */
color: blue;
}
.rem-text {
font-size: 1.5rem; /* 1.5 × 16px = 24px */
color: red;
}
</style>
</head>
<body>
<div class="container">
Container (20px font)
<div class="em-text">Em text (30px)</div>
<div class="rem-text">Rem text (24px)</div>
</div>
</body>
</html>
A container with 20px font size containing blue text at 30px (em-based) and red text at 24px (rem-based), demonstrating the difference between relative and root-relative sizing.
Conclusion
Relative units provide flexibility in CSS by scaling elements based on their context. Use percentage for layout proportions, em for component-based scaling, and rem for consistent sizing across your design.
Advertisements
