CHAPTER 40

CSS Units

Learn the different units used in CSS to control sizes, spacing, typography and responsive layouts.

01. What is CSS Units?

CSS units define measurements such as width, height, margin, padding and font size.
Common absolute units include px.
Common relative units include %, em, rem, vw and vh.
Relative units are important for responsive designs.

02. Syntax

selector { width: 100%; padding: 2rem; font-size: 1.2rem; }

03. Example

CSS / HTML Example AIFA Coding Lab
<!DOCTYPE html>
<html>
<head>

<style>

.container {

    width: 80%;

    min-height: 50vh;

    padding: 2rem;

    margin: 5vh auto;

    background: #dbeafe;

}

h1 {

    font-size: 3rem;

}

p {

    font-size: 1rem;

}

</style>

</head>

<body>

<div class="container">

    <h1>AIFA CSS</h1>

    <p>
        This example uses relative CSS units.
    </p>

</div>

</body>
</html>

04. Important Points

✓ px is a fixed CSS pixel unit.
✓ % is relative to a containing dimension.
✓ rem is relative to the root font size.
✓ em is relative to the font size of the relevant element.
✓ vw represents viewport width.
✓ vh represents viewport height.

05. Common Mistakes

⚠ Using only fixed pixels for every measurement.
⚠ Using em units without understanding their inheritance behavior.
⚠ Creating text sizes that become too large or too small on different screens.

06. Real World Use

CSS units are used everywhere in responsive websites, especially for typography, spacing, containers and viewport-based layouts.

Ready to Practice? 🚀

Open the AIFA CSS Editor and practice this chapter live.

Try It Yourself →
Practice Exercise

Practice Responsive Units

Create a container using %, rem and vh units. Resize the browser and observe how the layout changes.