Relative units help your website look good on different screen sizes and devices by adjusting sizes based on something else.
Relative units in 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.
font-size: 1.5em;
margin: 10%;
width: 50vw;
padding: 2rem;
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.
<!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>
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.
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.