CSS for Web Development

0% completed

Previous
Next
Relative units (em, rem, vw, vh)

Relative units allow you to design layouts that adapt to different environments. Unlike absolute units, these units depend on another value in your design. They help create scalable, flexible layouts and typography.

Em and Rem

  • em:
    • Relative to the font size of its parent element.
    • For example, if the parent has a font-size of 16px, 1em equals 16px, and 2em equals 32px.
  • rem (root em):
    • Relative to the root (HTML) element’s font size.
    • This ensures consistency because all rem values refer back to the same base size.

Example: Using Em and Rem for Font Sizing

HTML

. . . .

Explanation:

  • The html element sets the base font size to 16px, so 1rem equals 16px.
  • The h1 uses 2rem, making it 32px, and its margin-bottom of 0.5em is calculated relative to its font size (0.5 × 32px = 16px).
  • Paragraph text is set in em, meaning it scales with the parent's font size.

VW and VH

  • vw (viewport width):
    • 1vw is equal to 1% of the viewport’s width.
  • vh (viewport height):
    • 1vh is equal to 1% of the viewport’s height.

These units make it easy to create designs that adjust automatically to the size of the screen.

Example: Using VW and VH for a Responsive Layout

HTML

. . . .

Explanation:

  • The .full-screen-section uses 100vw and 100vh to always cover the full width and height of the viewport, regardless of device size.
  • The font size is set in vw, making the text size adjust with the viewport width, ensuring proportional scaling.

Relative units like em, rem, vw, and vh are essential for creating responsive and adaptive designs.

  • Em and rem ensure that text and spacing scale relative to font size, giving you control over typography.
  • VW and VH let you define sizes based on the viewport, enabling layouts to adjust dynamically to different screen dimensions.

Using these units helps build flexible designs that can adapt to various devices and user settings, ensuring a consistent experience across platforms.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next