LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 618 min read

CSS Units

Learn how CSS units control sizes, spacing, dimensions, typography, and responsive layouts using px, %, em, rem, vw, vh, and other measurement units.

Introduction

In the previous lesson, you learned how CSS colors control the visual appearance of text, backgrounds, borders, and other parts of a webpage.

Now you will learn how CSS controls size and measurement.

Every webpage contains measurements.

Text has a size, boxes have width and height, elements have spacing, borders have thickness, and layouts respond to different screen sizes.

CSS units tell the browser how large or small a value should be.

Choose CSS Property
↓
Write Numeric Value
↓
Add Appropriate Unit
↓
Browser Reads Reference
↓
Browser Calculates Size
↓
Display Final Result
Numbers Need Meaning

A value such as 20 does not always tell the browser what measurement you want. A unit such as px, %, rem, or vw gives the number meaning.

What are CSS Units?

CSS units are measurement values used to define the size, distance, spacing, position, and dimensions of elements.

Basic Unit Examples
.box {
width: 300px;
height: 150px;
margin: 20px;
padding: 1rem;
}

In these declarations, px and rem are CSS units.

CSS Measurement Structure
300px
300 → Numeric Value
px → Unit
Together → CSS Measurement
HTML
<div class="box">
CSS Units
</div>
CSS
.box {
width: 300px;
height: 100px;
font-size: 24px;
}
Live Preview
PropertyExample ValuePurpose
width300pxControls width
height200pxControls height
font-size18pxControls text size
margin20pxControls outer spacing
padding1remControls inner spacing
border-width2pxControls border thickness
top10%Controls position
gap2remControls spacing between layout items

Why Do We Need Units?

The browser needs to know how measurements should be calculated.

Different units allow developers to create fixed sizes, flexible sizes, scalable typography, and responsive layouts.

Different Measurement Goals
.fixed-box {
width: 300px;
}
.flexible-box {
width: 80%;
}
.scalable-text {
font-size: 2rem;
}
.screen-section {
height: 100vh;
}
RequirementPossible Unit
Fixed border thicknesspx
Flexible container width%
Scalable text sizerem
Component-relative spacingem
Full screen widthvw
Full screen heightvh

One Unit for Everything

  • Layouts may become rigid.
  • Text may not scale well.
  • Responsive design becomes difficult.
  • Components may behave unexpectedly.

Appropriate Units

  • Layouts can adapt.
  • Typography can scale.
  • Components become flexible.
  • Responsive design becomes easier.
Different Units Solve Different Problems

There is no single best CSS unit. The correct unit depends on what you are measuring and what the value should respond to.

Real-World Analogy

Imagine measuring objects in the real world.

You may use centimeters for a notebook, meters for a room, and percentages when describing how much space is occupied.

Real WorldCSS
Centimeterspx
Percentage of a room%
Size relative to another objectem
Size relative to a common standardrem
Percentage of screen widthvw
Percentage of screen heightvh
Measurement Analogy
Fixed Measurement
│
▼
px
Part of Available Space
│
▼
%
Relative to Text Size
│
├── em
└── rem
Relative to Screen
│
├── vw
└── vh
The Reference Point Matters

Relative units calculate their final size from another value. Understanding that reference value is the key to understanding CSS units.

CSS Value Structure

Many CSS measurements contain a number followed immediately by a unit.

Measurement Examples
width: 500px;
font-size: 2rem;
padding: 5%;
height: 100vh;
Value Structure
500px
│ │
│ └── Unit
│
└── Number
ValueNumberUnit
20px20px
50%50%
2em2em
1.5rem1.5rem
100vw100vw
100vh100vh
Do Not Add a Space

Write 20px, not 20 px. The number and unit must normally remain together.

Types of CSS Units

CSS units can be divided into two major categories: absolute units and relative units.

CategoryMeaningExamples
Absolute UnitsRepresent a generally fixed measurementpx, cm, mm, in, pt, pc
Relative UnitsCalculated relative to another value%, em, rem, vw, vh, vmin, vmax, ch
CSS Units
↓
Absolute Units
↓
Fixed Reference
↓
Relative Units
↓
Dynamic Reference
Unit Categories
CSS Units
│
├── Absolute Units
│ ├── px
│ ├── cm
│ ├── mm
│ ├── in
│ ├── pt
│ └── pc
│
└── Relative Units
├── %
├── em
├── rem
├── vw
├── vh
├── vmin
├── vmax
└── ch

Absolute vs Relative Units

Absolute units use a fixed reference, while relative units calculate their size from another value.

Absolute Units

  • Use a fixed measurement reference.
  • Do not depend directly on parent size.
  • Useful for precise small measurements.
  • px is the most commonly used absolute CSS unit.

Relative Units

  • Depend on another value.
  • Can adapt to containers or screens.
  • Useful for scalable interfaces.
  • Common in responsive design.
Absolute Example
.box {
width: 300px;
}
Relative Example
.box {
width: 50%;
}
Live Preview

1. Pixels (px)

The pixel unit is one of the most commonly used CSS units.

It is written using px.

Pixel Examples
.box {
width: 300px;
height: 150px;
padding: 20px;
border-width: 2px;
}
HTML
<div class="box">
300px Wide Box
</div>
CSS
.box {
width: 300px;
height: 100px;
background-color: #6c5ce7;
color: white;
}
Live Preview
Use CaseExample
Border thickness1px
Small icon size24px
Fixed component size300px
Small spacing8px
Border radius6px

Advantages of px

  • Easy to understand.
  • Predictable measurement.
  • Useful for precise details.
  • Common in design tools.

Limitations of px

  • Can create rigid layouts.
  • May require responsive adjustments.
  • Not always ideal for scalable typography.
  • Large fixed values may overflow small screens.
Pixels Are Not Bad

Pixels are useful for precise measurements such as borders, icons, and small details. Problems usually occur when every part of a responsive layout is forced into fixed pixel sizes.

2. Percentage (%)

Percentage values define a measurement relative to another size.

Percentage Example
.child {
width: 50%;
}

If the parent is 600px wide, a child with width: 50% becomes 300px wide.

Percentage Calculation
Parent Width = 600px
Child Width = 50%
600 × 50%
= 600 × 0.5
= 300px
HTML
<div class="parent">
<div class="child">
50% Width
</div>
</div>
CSS
.parent {
width: 100%;
}
.child {
width: 50%;
}
Live Preview
PercentagePart of Reference
25%One quarter
50%One half
75%Three quarters
100%Full reference size

Percentage Reference

A percentage value does not always use the same reference.

Its reference depends on the CSS property where the percentage is used.

PropertyPercentage Commonly Relates To
widthWidth of the containing block
heightHeight of the containing block when that reference is definite
font-sizeParent font size
line-heightElement font size
transform: translateX()Element width
transform: translateY()Element height
Different Percentage References
.child {
width: 50%;
font-size: 120%;
}
.move {
transform: translateX(50%);
}
Percentage Does Not Always Mean Parent Width

The reference for a percentage depends on the CSS property. Always understand what the specific property uses as its percentage reference.

3. em Unit

The em unit is a relative unit connected to font size.

For the font-size property, em is calculated relative to the font size of the parent element.

Basic em Example
.parent {
font-size: 20px;
}
.child {
font-size: 2em;
}

The child font size becomes 40px because 2em means two times the parent font size.

em Calculation
Parent Font Size = 20px
Child Font Size = 2em
20px × 2
= 40px
HTML
<div class="parent">
Parent Text
<div class="child">
Child Text
</div>
</div>
Live Preview
em Can Make Components Scale Together

When spacing and dimensions use em, changing the component font size can also scale related measurements.

How em is Calculated

The exact reference used by em depends on the property.

For font-size, em uses the inherited font size. For many other properties, em uses the calculated font size of the element itself.

Component Using em
.button {
font-size: 20px;
padding: 0.5em 1em;
}

Because the button font size is 20px, 0.5em becomes 10px and 1em becomes 20px.

Button Calculation
font-size = 20px
Vertical Padding:
0.5em × 20px = 10px
Horizontal Padding:
1em × 20px = 20px
Live Preview
Read em Value
↓
Find Relevant Font Size
↓
Multiply Value
↓
Calculate Final Size
↓
Render Element

The em Compounding Problem

Nested elements using em for font-size can multiply relative sizes repeatedly.

HTML
<div class="level-one">
Level One
<div class="level-two">
Level Two
<div class="level-three">
Level Three
</div>
</div>
</div>
CSS
.level-one,
.level-two,
.level-three {
font-size: 1.5em;
}

If the starting font size is 16px, each nested level becomes larger than the previous level.

LevelCalculationResult
Level One16px × 1.524px
Level Two24px × 1.536px
Level Three36px × 1.554px
Live Preview
Watch Nested em Font Sizes

When em is used for font-size on nested elements, the values can compound. This is one reason rem is often preferred for consistent typography.

4. rem Unit

The rem unit means root em.

It is calculated relative to the font size of the root html element.

Basic rem Example
html {
font-size: 16px;
}
h1 {
font-size: 2rem;
}

Because the root font size is 16px, 2rem becomes 32px.

rem Calculation
Root Font Size = 16px
Heading Size = 2rem
16px × 2
= 32px
HTML
<h1>2rem Heading</h1>
<p>1rem Paragraph</p>
CSS
html {
font-size: 16px;
}
h1 {
font-size: 2rem;
}
p {
font-size: 1rem;
}
Live Preview

How rem is Calculated

Every rem value refers back to the root font size rather than the immediate parent font size.

Root Reference
html {
font-size: 16px;
}
.small {
font-size: 0.75rem;
}
.normal {
font-size: 1rem;
}
.large {
font-size: 1.5rem;
}
.title {
font-size: 2rem;
}
rem ValueCalculationResult
0.75rem16 × 0.7512px
1rem16 × 116px
1.5rem16 × 1.524px
2rem16 × 232px
Nested Elements Still Use Root
html {
font-size: 16px;
}
.parent {
font-size: 30px;
}
.child {
font-size: 2rem;
}

The child becomes 32px, not 60px, because rem uses the root font size rather than the parent font size.

rem Creates Consistent Scaling

Because rem uses one root reference, it is useful for consistent typography and spacing systems.

em vs rem

em

  • Relative to a font-size reference.
  • For font-size, uses the parent font size.
  • Can compound in nested elements.
  • Useful for component-relative scaling.

rem

  • Relative to the root font size.
  • Uses one consistent reference.
  • Does not compound through nesting.
  • Useful for global typography and spacing.
em Example
.parent {
font-size: 20px;
}
.child {
font-size: 2em;
}
/* Result: 40px */
rem Example
html {
font-size: 16px;
}
.parent {
font-size: 20px;
}
.child {
font-size: 2rem;
}
/* Result: 32px */
Featureemrem
Main ReferenceFont size contextRoot font size
Affected by nestingCan beNo
Component scalingExcellentGood
Global consistencyCan require careExcellent
Common useComponent-relative sizingTypography and spacing

5. Viewport Width (vw)

The vw unit is relative to the width of the viewport.

One vw represents one percent of the viewport width.

vw Meaning
1vw = 1% of Viewport Width
50vw = 50% of Viewport Width
100vw = 100% of Viewport Width
vw Example
.box {
width: 50vw;
}

If the viewport is 1200px wide, 50vw becomes 600px.

vw Calculation
Viewport Width = 1200px
50vw = 50% of 1200px
1200 × 0.5
= 600px
Live Preview
vw Follows the Browser Width

When the viewport width changes, a vw-based measurement changes with it.

6. Viewport Height (vh)

The vh unit is relative to the height of the viewport.

One vh represents one percent of the viewport height.

vh Meaning
1vh = 1% of Viewport Height
50vh = 50% of Viewport Height
100vh = 100% of Viewport Height
Full Screen Section
.hero {
min-height: 100vh;
}
HTML
<section class="hero">
Full Screen Hero Section
</section>
Live Preview
Common for Hero Sections

Viewport height units are commonly used when a section should fill a large portion or all of the visible screen.

vw and vh Calculation

Viewport units are calculated directly from the browser viewport dimensions.

Example Viewport
Viewport Width = 1200px
Viewport Height = 800px
1vw = 12px
1vh = 8px
ValueCalculationResult
10vw1200 × 10%120px
25vw1200 × 25%300px
50vw1200 × 50%600px
10vh800 × 10%80px
50vh800 × 50%400px
100vh800 × 100%800px
Read Viewport Size
↓
Read vw or vh Value
↓
Convert to Percentage
↓
Calculate Pixels
↓
Render Final Size

7. vmin Unit

The vmin unit uses the smaller viewport dimension.

vmin Reference
Viewport:
Width = 1200px
Height = 800px
Smaller Dimension = 800px
1vmin = 1% of 800px
= 8px
vmin Example
.shape {
width: 30vmin;
height: 30vmin;
}
Live Preview
Useful for Shapes

vmin can help create elements that remain proportional to the smaller side of the screen.

8. vmax Unit

The vmax unit uses the larger viewport dimension.

vmax Reference
Viewport:
Width = 1200px
Height = 800px
Larger Dimension = 1200px
1vmax = 1% of 1200px
= 12px
vmax Example
.background-shape {
width: 50vmax;
height: 50vmax;
}
UnitReference
vwViewport width
vhViewport height
vminSmaller viewport dimension
vmaxLarger viewport dimension
Large vmax Values Can Become Very Large

Because vmax follows the larger viewport dimension, large values can easily extend beyond the visible screen.

9. ch Unit

The ch unit is based on the width of the zero character in the current font.

It is especially useful for controlling readable text line lengths.

Readable Text Width
.article {
max-width: 65ch;
}
HTML
<p class="article">
Long paragraphs are easier to read when
the line length is controlled.
</p>
Live Preview
Useful for Article Content

A max-width measured in ch is commonly useful for paragraphs, documentation, articles, and other text-heavy content.

10. Unitless Values

Some CSS properties accept numbers without any unit.

Unitless Examples
.text {
line-height: 1.6;
}
.item {
flex-grow: 1;
}
.layer {
z-index: 10;
}
.transparent {
opacity: 0.5;
}
PropertyExampleUnit Required?
line-height1.6No
opacity0.5No
z-index10No
font-weight700No
flex-grow1No
HTML
<p class="text">
This paragraph uses a unitless line-height.
</p>
CSS
.text {
font-size: 20px;
line-height: 1.6;
}

A unitless line-height of 1.6 means the line height is calculated as 1.6 times the element font size.

Line Height Calculation
Font Size = 20px
Line Height = 1.6
20px × 1.6
= 32px
Do Not Remove Units Everywhere

Only use unitless numbers where the CSS property allows them. A width such as width: 300 usually does not create a valid length.

Common CSS Units

UnitNameRelative ToCommon Use
pxPixelCSS pixel referenceBorders and precise sizes
%PercentageProperty-specific referenceFlexible widths
emEmFont-size contextComponent scaling
remRoot EmRoot font sizeTypography and spacing
vwViewport WidthViewport widthScreen-based widths
vhViewport HeightViewport heightScreen-based heights
vminViewport MinimumSmaller viewport dimensionResponsive shapes
vmaxViewport MaximumLarger viewport dimensionLarge responsive effects
chCharacter UnitWidth of zero characterReadable text widths
Multiple Units Together
.page {
width: 90%;
max-width: 1200px;
min-height: 100vh;
padding: 2rem;
}
.article {
max-width: 65ch;
}
.title {
font-size: 3rem;
}
.button {
padding: 0.75em 1.5em;
border: 2px solid;
}
Real Projects Mix Units

Professional stylesheets commonly combine different units because each unit is suited to a different type of measurement.

Choosing the Right Unit

Choosing a unit depends on what the measurement should respond to.

RequirementCommon Choice
Thin borderpx
Flexible container width%
Maximum page widthpx or rem
Global text sizerem
Component-relative paddingem
Full viewport sectionvh
Viewport-based widthvw
Readable paragraph widthch
Responsive circular shapevmin
What Are You Measuring?
↓
Should It Be Fixed?
↓
Should It Follow Parent?
↓
Should It Follow Text?
↓
Should It Follow Screen?
↓
Choose Appropriate Unit

Fixed Requirement

  • Small borders.
  • Precise icons.
  • Minor visual details.
  • Controlled maximum sizes.

Flexible Requirement

  • Responsive containers.
  • Scalable typography.
  • Full-screen sections.
  • Adaptive spacing.
Ask What the Value Should Follow

If the size should follow a container, screen, font size, or root size, choose a unit based on that relationship.

Complete Responsive Example

The following example combines several CSS units in one responsive component.

HTML
<section class="hero">
<div class="hero-content">
<span class="badge">
CSS Course
</span>
<h1>
Learn Modern CSS
</h1>
<p>
Build responsive and scalable
websites step by step.
</p>
<button>
Start Learning
</button>
</div>
</section>
CSS
.hero {
min-height: 80vh;
width: 100%;
padding: 3rem 5%;
}
.hero-content {
width: 90%;
max-width: 65ch;
}
.badge {
font-size: 0.875rem;
padding: 0.5em 1em;
}
h1 {
font-size: 3rem;
}
p {
font-size: 1.125rem;
line-height: 1.7;
}
button {
font-size: 1rem;
padding: 0.75em 1.5em;
border: 2px solid;
}
Live Preview
UnitUsed For
vhHero minimum height
%Responsive width and horizontal padding
chReadable content width
remTypography and major spacing
emButton and badge spacing
pxBorder thickness
Use % for Flexible Width
↓
Use vh for Screen Height
↓
Use rem for Global Scale
↓
Use em for Component Scale
↓
Use ch for Text Width
↓
Use px for Fine Details

Browser Calculation Flow

The browser must convert CSS measurements into final values before drawing elements.

Read CSS Property
↓
Read Numeric Value
↓
Identify Unit
↓
Find Reference Value
↓
Calculate Final Measurement
↓
Build Layout
↓
Paint Element
↓
Display Page
Unit Calculation Process
CSS Value
│
▼
Read Number
│
▼
Read Unit
│
├── px → Use Pixel Reference
├── % → Find Property Reference
├── em → Find Font Size Reference
├── rem → Find Root Font Size
├── vw → Read Viewport Width
└── vh → Read Viewport Height
│
▼
Calculate Final Value
│
▼
Create Layout
│
▼
Display Output
ValueBrowser Reference
300pxCSS pixel reference
50%Property-specific reference
2emRelevant font size
2remRoot font size
50vwViewport width
50vhViewport height
Relative Values Become Calculated Sizes

The browser uses the relevant reference value to calculate the final size used for layout and rendering.

Real-World Applications

CSS units are used in every part of modern website development.

Responsive Layouts

Use percentages and viewport units to create flexible interfaces.

Typography

Use rem and em to create scalable text systems.

Components

Use em for buttons, badges, and component-relative spacing.

Hero Sections

Use viewport units for screen-based sections.

Articles

Use ch to control readable text line lengths.

Precise Details

Use pixels for borders, icons, and fine visual details.

Cards

Combine percentages, rem, and px for flexible card layouts.

Design Systems

Use consistent unit strategies for spacing and typography.

Understand Design Requirement
↓
Identify Reference
↓
Choose Unit
↓
Calculate Responsively
↓
Test Different Screens

Advantages

CSS units provide multiple ways to create precise, flexible, scalable, and responsive designs.

Precise Control

Pixels provide control for small and exact visual details.

Responsive Design

Relative units allow layouts to adapt to available space.

Scalable Typography

rem and em support flexible text sizing.

Flexible Components

Component measurements can scale with their text size.

Screen-Based Layouts

Viewport units respond directly to browser dimensions.

Better Readability

The ch unit helps control comfortable text line lengths.

Reusable Systems

Consistent units support reusable spacing and typography scales.

Design Flexibility

Different units can be combined for different design requirements.

Common Beginner Mistakes

Adding a Space Between Number and Unit

Write 20px, not 20 px.

Forgetting the Unit

A length such as width: 300 is usually invalid because the browser does not know which length unit to use.

Adding Units to Unitless Properties

Properties such as opacity and z-index use unitless values.

Using px for Everything

Large fixed pixel values can create rigid layouts that do not adapt well.

Assuming Percentage Always Uses Parent Width

The percentage reference depends on the CSS property.

Expecting Percentage Height to Always Work

Percentage heights often require a definite height reference from the containing block.

Confusing em and rem

em uses a font-size context, while rem always refers to the root font size.

Ignoring em Compounding

Nested font sizes using em can multiply repeatedly.

Assuming rem Uses Parent Font Size

rem uses the root html font size.

Assuming em Always Uses Parent Font Size

For font-size it uses the inherited parent size, but for many other properties it uses the element calculated font size.

Confusing vw with Percentage Width

vw is based on the viewport, while percentages use a property-specific reference.

Confusing vh with Parent Height

vh is based on the viewport height.

Using 100vw Without Considering Overflow

A full viewport width can sometimes contribute to horizontal overflow depending on the page and scrollbar behavior.

Using Large vh Values for All Mobile Layouts

Mobile browser interface changes can affect visible viewport behavior, so screen-height layouts should be tested carefully.

Using Huge vmin or vmax Values

Viewport-relative values can become unexpectedly large on some screen shapes.

Assuming ch Means Exact Character Count

ch is based on the width of the zero character and does not guarantee an exact number of visible characters.

Using Fixed Width Without max-width

A large fixed width can overflow smaller screens.

Mixing Units Randomly

Different units should be chosen according to clear sizing relationships.

Changing the Root Font Size Without Understanding rem

Changing the html font size affects every rem-based measurement.

Not Testing Responsive Sizes

Relative units should be tested across small and large screens.

Best Practices

  • Choose units according to what the measurement should respond to.
  • Use px for precise small visual details.
  • Use px carefully for large layout dimensions.
  • Avoid forcing every layout measurement into fixed pixels.
  • Use percentages for flexible widths when appropriate.
  • Understand the reference used by each percentage value.
  • Do not assume every percentage is relative to parent width.
  • Use rem for consistent global typography.
  • Use rem for reusable spacing scales when appropriate.
  • Understand that rem always refers to the root font size.
  • Use em when a component should scale with its text size.
  • Use em for component-relative padding when useful.
  • Watch for compounding when using em for nested font sizes.
  • Understand that em references can depend on the property.
  • Use vw for measurements that should follow viewport width.
  • Use vh for measurements that should follow viewport height.
  • Test viewport-based layouts on multiple screen sizes.
  • Test viewport-height layouts on mobile devices.
  • Use vmin when a measurement should follow the smaller viewport dimension.
  • Use vmax carefully because values can become very large.
  • Use ch to control readable text line lengths.
  • Do not treat ch as an exact character counter.
  • Use unitless line-height when appropriate.
  • Use unitless values only where the property allows them.
  • Do not add px to opacity values.
  • Do not add px to z-index values.
  • Do not add px to flex-grow values.
  • Do not place spaces between numbers and units.
  • Write 20px instead of 20 px.
  • Remember that zero can often be written without a unit.
  • Use 0 instead of 0px when the unit adds no useful meaning.
  • Combine units intentionally.
  • Use % for flexible containers.
  • Use max-width to prevent content from becoming too wide.
  • Use min-width carefully to avoid overflow.
  • Use max-width with large fixed widths when responsive behavior is required.
  • Use min-height instead of fixed height when content may grow.
  • Avoid fixed heights for text-heavy components.
  • Allow content to determine height when possible.
  • Use viewport units for screen-relative design effects.
  • Avoid using viewport units for every measurement.
  • Use rem for headings and body text when building a scalable type system.
  • Use consistent spacing units throughout a project.
  • Create a spacing scale instead of choosing random values.
  • Use consistent typography ratios.
  • Avoid random combinations such as 13px, 1.27rem, and 2.8em without a design reason.
  • Document the unit strategy in large projects.
  • Keep component units predictable.
  • Use relative units when the design should adapt.
  • Use fixed units when the measurement should remain controlled.
  • Understand the difference between viewport and container references.
  • Remember that 50vw means half the viewport width.
  • Remember that width: 50% does not necessarily equal 50vw.
  • Remember that 100vh means the full viewport height reference.
  • Remember that 1rem equals one root font size.
  • Remember that 1em depends on a font-size context.
  • Check inherited font sizes before debugging em calculations.
  • Check the html font size before debugging rem calculations.
  • Check parent or containing-block dimensions before debugging percentages.
  • Check viewport dimensions before debugging vw and vh.
  • Use browser developer tools to inspect computed values.
  • Inspect the final pixel value calculated by the browser.
  • Resize the browser while testing relative units.
  • Test narrow mobile screens.
  • Test wide desktop screens.
  • Test portrait orientation.
  • Test landscape orientation.
  • Check for horizontal overflow.
  • Check whether fixed widths exceed the available space.
  • Use box-sizing appropriately when dimensions include padding and borders.
  • Remember that width calculations can interact with padding and borders.
  • Do not blame the unit before checking the box model.
  • Use max-width for responsive images and containers.
  • Use min() and max() when combining responsive limits in advanced layouts.
  • Use clamp() when a value needs minimum, preferred, and maximum limits.
  • Learn modern viewport units when building complex mobile full-screen interfaces.
  • Use dvh, svh, and lvh when their specific viewport behavior is needed.
  • Do not introduce advanced units before understanding basic viewport units.
  • Keep beginner code simple before optimizing the unit strategy.
  • Choose readability over clever calculations.
  • Use relative units consistently in design systems.
  • Use absolute units where precision is genuinely required.
  • Avoid unnecessary unit conversions.
  • Do not convert px to rem only to make the code appear modern.
  • Use rem when root-relative behavior is actually useful.
  • Use em when component-relative behavior is actually useful.
  • Use % when container-relative behavior is useful.
  • Use viewport units when viewport-relative behavior is useful.
  • Use ch when text-width behavior is useful.
  • Understand the reference before choosing the unit.
  • Test the result rather than relying only on calculations.
  • Check accessibility when sizing text.
  • Avoid making essential text extremely small.
  • Allow browser zoom to remain useful.
  • Avoid layouts that break when text becomes larger.
  • Test components with longer content.
  • Test buttons with longer labels.
  • Test cards with multiple lines of text.
  • Test headings on small screens.
  • Use responsive limits for very large text.
  • Use flexible widths for reusable components.
  • Avoid fixed widths for unknown content.
  • Keep line lengths comfortable for reading.
  • Use a maximum text width for articles.
  • Use consistent units for related values.
  • Keep the sizing system understandable.
  • Keep the sizing system responsive.
  • Keep the sizing system maintainable.
Choose Units by Relationship

Use px for precise details, % for container relationships, rem for root-relative scaling, em for component-relative scaling, and viewport units for screen relationships.

Frequently Asked Questions

A CSS unit defines how a numeric measurement such as width, height, spacing, or font size should be interpreted.

CSS units are commonly grouped into absolute units and relative units.

An absolute unit uses a generally fixed measurement reference. The most commonly used example in screen design is px.

A relative unit calculates its final value from another reference such as a parent size, font size, root font size, or viewport size.

px means pixel and is commonly used for precise CSS measurements.

No. Pixels are useful for many measurements. Problems occur when large fixed sizes are used without considering smaller screens.

A percentage creates a value relative to a reference determined by the CSS property.

No. It is commonly half the width of the containing block, not necessarily half the viewport.

Percentage heights often need a definite height reference from the containing block.

em is a relative unit connected to font size.

It means two times the relevant font-size reference.

For font-size, it uses the inherited parent font size. For many other properties, it uses the calculated font size of the element.

Nested elements using em for font-size can repeatedly multiply the inherited size.

rem means root em and is relative to the root html element font size.

It equals one root font size.

No. It is often 16px by default, but it depends on the root font size and user or browser settings.

em uses a font-size context, while rem always uses the root font size.

Neither is always better. rem is useful for global consistency, while em is useful when a component should scale relative to its own text size.

vw means viewport width. One vw equals one percent of the viewport width.

It represents the full viewport width reference.

vh means viewport height. One vh equals one percent of the viewport height.

It represents the full viewport height reference.

A percentage uses a property-specific reference, while 100vw uses the viewport width.

A percentage height depends on a containing-block height reference, while 100vh uses the viewport height.

vmin uses the smaller of the viewport width and viewport height.

vmax uses the larger of the viewport width and viewport height.

ch is based on the width of the zero character in the current font.

It is useful for controlling readable text widths, such as limiting an article to around 60 or 70ch.

No. Character widths vary, so ch does not guarantee an exact visible character count.

Yes. Some properties accept unitless numbers, such as opacity, z-index, flex-grow, and unitless line-height.

In many CSS length contexts, zero can be written without a unit.

Both may work in many length contexts, but 0 is usually simpler.

A non-zero CSS length normally needs a unit, such as width: 300px.

The number and unit must remain together, so write 20px.

rem is commonly useful for global typography, while em can be useful for component-relative text sizing.

It depends on the design. Percentages are useful for flexible widths, pixels or rem can provide limits, and viewport units can create screen-relative widths.

rem is useful for consistent global spacing, while em is useful when spacing should scale with a component font size.

Pixels are commonly used for thin and precise border widths.

Yes. Real projects commonly combine multiple units according to different sizing requirements.

The next lesson covers CSS backgrounds, including background colors, images, repeat behavior, position, size, attachment, and shorthand syntax.

Key Takeaways

  • CSS units define measurements.
  • Measurements are used for width, height, spacing, typography, borders, and positioning.
  • Many CSS measurements contain a number and a unit.
  • Write the number and unit together.
  • Write 20px, not 20 px.
  • CSS units can be absolute or relative.
  • Absolute units use a generally fixed reference.
  • Relative units calculate values from another reference.
  • px is the most commonly used absolute unit for screen design.
  • Pixels are useful for precise measurements.
  • Large fixed pixel values can create rigid layouts.
  • Percentage values are relative.
  • The reference for a percentage depends on the property.
  • width: 50% commonly means half the containing block width.
  • em is connected to font size.
  • For font-size, em uses the inherited parent font size.
  • Nested em font sizes can compound.
  • rem means root em.
  • rem always uses the root font size.
  • 1rem equals one root font size.
  • rem is useful for consistent typography.
  • em is useful for component-relative scaling.
  • vw is relative to viewport width.
  • 1vw equals one percent of viewport width.
  • vh is relative to viewport height.
  • 1vh equals one percent of viewport height.
  • 100vh represents the full viewport height reference.
  • vmin uses the smaller viewport dimension.
  • vmax uses the larger viewport dimension.
  • ch is based on the width of the zero character.
  • ch is useful for readable text widths.
  • Some CSS properties accept unitless values.
  • opacity is unitless.
  • z-index is unitless.
  • Unitless line-height can scale with font size.
  • Different units solve different problems.
  • Real projects commonly combine several units.
  • Use px for precise details.
  • Use % for flexible container relationships.
  • Use rem for root-relative scaling.
  • Use em for component-relative scaling.
  • Use viewport units for screen-relative measurements.
  • Use ch for text-width control.
  • Understand the reference before choosing a unit.
  • Test relative units across different screen sizes.
  • A good unit strategy improves responsiveness and maintainability.

Summary

CSS units tell the browser how measurements such as width, height, spacing, typography, and positioning should be calculated.

Absolute units use a generally fixed measurement reference, while relative units calculate their values from another reference.

Pixels are commonly used for precise measurements such as borders, icons, and controlled dimensions.

Percentages create flexible values based on a reference determined by the CSS property.

The em unit is connected to font size and can be useful for component-relative scaling.

Nested em font sizes can compound because each level may use the calculated size of its parent.

The rem unit uses the root font size and provides a consistent reference for typography and spacing.

Viewport units such as vw and vh create measurements based on the width and height of the browser viewport.

The vmin and vmax units use the smaller and larger viewport dimensions.

The ch unit is useful for controlling readable text widths.

Some CSS properties accept unitless values, including opacity, z-index, flex-grow, and unitless line-height.

Professional CSS commonly combines multiple units because each unit is designed for a different relationship.

The best unit depends on what the measurement should follow: a fixed reference, a container, a font size, the root font size, or the viewport.

In the next lesson, you will learn CSS backgrounds and understand how to use background colors, images, repeat behavior, positioning, sizing, attachment, and shorthand properties.

Next Lesson →

Backgrounds