Home 〉 CSS Tutorials 〉 CSS Tutorial for Beginners: Learn CSS Step by Step with Examples
CSS Units Explained: px, em, rem, %, vh, vw & More (With Examples) !
Not sure which CSS units to use for sizing elements?
This guide breaks down various CSS units like pixels (px), em, rem, percentages (%), viewport height (vh), and viewport width (vw). Understand how each unit works and when to use them for responsive and scalable designs.
Understanding CSS units is essential to building responsive, clean, and flexible web designs. This guide will walk you through 'all common CSS units', explain what each one means, how it calculates value, and give you simple examples for every unit. Let's get started!
In this Tutorial, we are going to cover the following CSS 'Units':
Example 📄
h1 {
font-size: 24px;
}
This means the font size is exactly 24 pixels, no matter the screen size.
Example 📄
div {
width: 50%;
}
This means the `<div>` will take 50% of the width of its parent.
Example 📄
p {
font-size: 1.5em;
}
If the parent's font size is 16px, then `1.5em` = 24px.
Example 📄
body {
font-size: 1.25rem;
}
If root font-size is 16px, this means 1.25rem = 20px.
Example 📄
section {
height: 100vh;
}
This means the section takes 100% of the browser height.
Example 📄
h1 {
font-size: 5vw;
}
Font size will change as the browser width changes.
Example 📄
.box {
font-size: 2vmin;
}
The text size adapts to the smaller of screen width or height.
Example 📄
input {
width: 20ch;
}
The input field fits about 20 characters.
Example 📄
p {
line-height: 2ex;
}
Unit | Relative to | Typical Use |
---|---|---|
px | Fixed | Exact sizing |
% | Parent size | Responsive layouts |
em | Parent font | Nested scaling |
rem | Root font | Consistent scaling |
vh | Viewport H | Full-height elements |
vw | Viewport W | Responsive font/layouts |
vmin | Smaller of vh/vw | Responsive UIs |
vmax | Larger of vh/vw | Responsive UIs |
ch | Character width | Form inputs, readable widths |
ex | Font x-height | Typography fine-tuning |
There's no one best unit. It depends on what you're building. Use `px` for fixed sizes, `rem` or `em` for scalable text, and `%`, `vw`, or `vh` for responsive designs.
Use `rem` when you want your design to scale better on different screen sizes. It also helps with accessibility, like increasing text size in browsers.
It means “1 root em.” If your root (html) font size is 16px, then 1rem = 16px.
It means 100% of the viewport height. So, if your screen height is 800px, 100vh = 800px.
No. `%` is based on the parent element's size. `vw` and `vh` are based on the browser window's width and height.
Yes! You can mix units like `calc(100% - 20px)` to get flexible layouts. Just be careful so it doesn't get confusing.
Use `%`, `vw`, `vh`, and `rem` to make layouts that adjust to different screen sizes and devices.
The default root font size is usually 16px*in most browsers. So, 1rem = 16px by default unless you change it.
They help make things flexible based on screen size.