RELATIVE UNITS
% (Percentage)
.container {
width: 50%;
}
👉 Relative to parent element
Example:
.parent {
width: 400px;
}
.child {
width: 50%; /* = 200px */
}
em (Relative to Parent Font Size)
.parent {
font-size: 20px;
}
.child {
font-size: 2em; /* = 40px */
}
👉 1em = parent font-size
⚠️ Problem with em (IMPORTANT)
It can stack and grow unexpectedly
.parent {
font-size: 20px;
}
.child {
font-size: 2em; /* 40px */
}
.grandchild {
font-size: 2em; /* 80px 😵 */
}
rem (ROOT EM) — BEST PRACTICE ✅
html {
font-size: 16px;
}
h1 {
font-size: 2rem; /* = 32px */
}
👉 Always based on <html>
✔️ Why use rem?
- Consistent
- Predictable
- Responsive friendly
vw (Viewport Width)
div {
width: 50vw;
}
👉 50% of screen width
vh (Viewport Height)
div {
height: 100vh;
}
👉 Full screen height
🔥 Real Example:
.hero {
height: 100vh;
}
👉 Full screen hero section
vmin & vmax
div {
width: 50vmin;
}
👉 Based on smaller/larger screen dimension