0
0
CSSmarkup~5 mins

Relative units in CSS

Choose your learning style9 modes available
Introduction

Relative units help your website look good on different screen sizes and devices by adjusting sizes based on something else.

Making text size adjust when the user changes their browser settings.
Creating layouts that fit well on both phones and big screens.
Spacing elements so they scale nicely when the page size changes.
Setting widths or heights that depend on the size of the parent container.
Adjusting sizes based on the user's default font size for better accessibility.
Syntax
CSS
property: valueunit;

Relative units depend on something else, like the size of the parent or the root element.

Common relative units include em, rem, %, vw, and vh.

Examples
Text size is 1.5 times the size of its parent element's font size.
CSS
font-size: 1.5em;
Margin is 10% of the width of the parent element.
CSS
margin: 10%;
Width is 50% of the viewport's width (the visible part of the browser window).
CSS
width: 50vw;
Padding is 2 times the root element's font size, usually the browser default.
CSS
padding: 2rem;
Sample Program

This example shows a box that is half the width of the browser window. The text sizes and spacing use relative units so they scale nicely if you resize the window or change your browser's font size.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Relative Units Example</title>
  <style>
    :root {
      font-size: 16px;
    }
    body {
      font-family: Arial, sans-serif;
      margin: 2rem;
    }
    .container {
      width: 50vw;
      padding: 1rem;
      border: 2px solid #4a90e2;
      background-color: #e6f0fa;
    }
    h1 {
      font-size: 2rem;
      margin-bottom: 1rem;
    }
    p {
      font-size: 1.2em;
      margin-bottom: 1rem;
    }
    button {
      font-size: 1rem;
      padding: 0.5em 1em;
      background-color: #4a90e2;
      color: white;
      border: none;
      border-radius: 0.3rem;
      cursor: pointer;
    }
    button:hover {
      background-color: #357abd;
    }
  </style>
</head>
<body>
  <main class="container" role="main">
    <h1>Relative Units Demo</h1>
    <p>This box is 50% of the viewport width (50vw).</p>
    <p>The font sizes and spacing use <code>rem</code> and <code>em</code> units.</p>
    <button aria-label="Click me button">Click Me</button>
  </main>
</body>
</html>
OutputSuccess
Important Notes

em units are relative to the font size of the parent element.

rem units are relative to the root (html) font size, usually 16px by default.

Viewport units like vw and vh depend on the browser window size, useful for responsive design.

Summary

Relative units help your page adapt to different screen sizes and user settings.

Use em for sizes relative to the parent element's font size.

Use rem for sizes relative to the root font size, and vw/vh for viewport-based sizes.