Back to course

Lesson 22: Understanding CSS Units: Pixels (px) and Percentage (%)

CSS Mastery: From Zero to Hero in 100 Lessons

22. Understanding CSS Units: Pixels (px) and Percentage (%)

CSS needs units to quantify dimensions, spacing, and font sizes. We categorize them as absolute (fixed) or relative (fluid/scalable).

1. Absolute Units: Pixels (px)

Pixels are the standard fixed unit. 1px refers to one physical dot on the screen (though modern screens complicate this, conceptually it's a fixed size).

  • Usage: Define specific, unchangeable sizes for borders, shadows, or when you need guaranteed precision.
  • Pros: Precise and predictable.
  • Cons: Not scalable for different devices. Fixed text sizes can be hard for users with low vision to scale.

css .icon { width: 32px; height: 32px; }

.divider { border-bottom: 1px solid #ccc; }

2. Relative Units: Percentage (%)

Percentage units are relative to the dimension of the immediate parent element.

  • Usage: Creating fluid layouts where elements scale with the container size.
  • Pros: Excellent for responsive design and fluid containers.
  • Cons: Can be confusing. If a child element has width: 50%, and its parent has width: 50% of its parent, the child ends up being 25% of the original grandparent.

css .parent { width: 800px; }

.child { width: 50%; /* 400px wide / padding: 5%; / 5% of 800px = 40px padding */ }