CSS Units
CSS Units
CSS units define the size of things like text, spacing, widths, and heights. Choosing the right unit helps you build layouts that look good on different screen sizes and remain accessible.
CSS units are mainly grouped into two categories: absolute units and relative units.
Units
Units are used in properties such as:
font-size,line-heightmargin,paddingwidth,heightborder-width,border-radius
Example:
.card {
padding: 16px;
border-radius: 12px;
width: 320px;
}
Absolute Units
Absolute units are fixed. They do not scale based on the screen or the user’s font settings (in most cases).
px– pixels (most common)cm,mm– centimeters, millimetersin– inchespt– points (often used in print)pc– picas
In web design, px is the most widely used absolute unit.
.box {
width: 300px;
border: 2px solid #ddd;
}
Relative Units
Relative units scale based on something else, such as the parent size, the root font size, or the viewport. These units are often better for responsive design and accessibility.
%– relative to the parentem– relative to the font size of the elementrem– relative to the root (html) font sizevw– 1% of the viewport widthvh– 1% of the viewport height
Percent (%)
Percent values are relative to the parent element. This is often used for flexible widths.
.container {
width: 600px;
}
.child {
width: 50%;
}
em vs rem
em is based on the current element’s font size, while rem is based on the root font size.
html {
font-size: 16px;
}
.title {
font-size: 2rem; /* 32px */
}
.note {
font-size: 1.25em; /* depends on parent font-size */
}
rem is often preferred for consistent scaling across the entire page.
Viewport Units (vw / vh)
Viewport units are relative to the browser window size.
.hero {
height: 60vh;
}
.full-width {
width: 100vw;
}
These units are useful for full-screen sections and responsive hero areas.
Which Unit Should I Use?
- Use
remfor font sizes and spacing (consistent and scalable) - Use
%for flexible widths - Use
vw/vhfor viewport-based layouts - Use
pxfor borders and fine details
Code Challenge
Goal: Build a responsive card using a mix of units.
HTML:
<div class="card"> <h3>Units</h3> <p>This card uses rem, %, and px.</p> </div>
Task:
- Set the card width to
90%and limit it usingmax-width - Use
remfor padding and font sizes - Use
pxfor borders
Try a Solution:
.card {
width: 90%;
max-width: 520px;
margin: 40px auto;
padding: 1.25rem;
border: 1px solid #ddd;
border-radius: 12px;
box-sizing: border-box;
}
.card h3 {
font-size: 1.5rem;
margin-top: 0;
}
.card p {
font-size: 1rem;
line-height: 1.7;
}
What’s Next?
Next, you will learn how CSS inheritance works and which properties are inherited by default.