C

CSS Handbook

Clean • Professional

Viewport & CSS Units

2 minute

Viewport & CSS Units

When building responsive websites, two things matter the most:

  1. Viewport settings (how the browser displays a webpage on different screens).
  2. CSS units (how we size elements like text, boxes, or layouts).

Let’s break this down step by step : -

Meta Viewport Basics

By default, mobile browsers shrink webpages to fit a desktop width, which makes text too small and layouts broken.

To fix this, we use the viewport meta tag in the <head> section of HTML.

Example (Meta Viewport)

  • width=device-width → Matches the screen width of the device.
  • initial-scale=1.0 → Ensures no zooming when the page first loads.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <!-- Viewport meta tag -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Meta Viewport Example</title>
</head>
<body>
  <h1>Hello, Responsive World!</h1>
  <p>This page adapts to your device screen size.</p>
</body>
</html>

CSS Units Overview

CSS provides different units for sizing elements. They can be grouped into two categories:

1. Relative Units

These units scale based on other values (like parent or root font size).

  • % (Percentage) → Relative to parent element.
  • em → Relative to the parent’s font size.
  • rem → Relative to the root (HTML) font size.

Example (Relative Units)

 <h1>Relative Units Demo</h1>
  <div class="parent">
    Parent Text
    <p class="child">Child Text</p>
  </div>

html {
  font-size: 16px; /* base font size */
}

.parent {
  font-size: 20px; /* parent font size */
  margin: 5%;
}

.child {
  font-size: 1.5em; /* 1.5 × parent's font size = 30px */
  margin: 2rem;     /* 2 × root font size = 32px */
}

2. Viewport Units

These units adjust based on the browser window (viewport) size.

  • vw (Viewport Width) → 1vw = 1% of browser width.
  • vh (Viewport Height) → 1vh = 1% of browser height.
  • vmin → The smaller of vw or vh.
  • vmax → The larger of vw or vh.

Example (Viewport Units)

<header>
    <h1>Viewport Units Demo</h1>
  </header>
  <section class="hero">
    <p>This section takes full screen height & width.</p>
  </section>
body {
  margin: 0;
  font-family: Arial, sans-serif;
}

header {
  background: #0078d7;
  color: white;
  text-align: center;
  padding: 2vh; /* 2% of screen height */
}

.hero {
  background: #28a745;
  color: white;
  height: 100vh;  /* 100% of viewport height */
  width: 100vw;   /* 100% of viewport width */
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 3vmin; /* Scales with smaller side */
}

 

Article 0 of 0