How Do You Give 100% Height and Width in CSS?

Creating layouts that span the full height and width of the browser window or parent element is a common requirement in web development. In CSS, setting elements to 100% height and width can seem simple, but it requires an understanding of how CSS calculates percentage values and how parent containers are structured.

In this post, we’ll cover how to give elements 100% height and width in CSS — and how to make sure it works as expected.


✅ Setting 100% Height and Width: The Basics

To make an element fill the entire width and height of its parent, you can use:

.full-size {
  width: 100%;
  height: 100%;
}

But here’s the catch: For this to work properly, the parent element must have an explicit height set.


🧱 Example: Full Page Layout

Let’s say you want a div to cover the full browser window:

HTML

<body>
  <div class="full-screen"></div>
</body>

CSS

html, body {
  height: 100%;
  margin: 0;
}

.full-screen {
  width: 100%;
  height: 100%;
  background-color: lightblue;
}

Why this works:

  • html and body are set to 100% height.
  • The .full-screen div can now use height: 100% relative to them.

🧠 Important Rules to Remember

  1. Percentage heights are relative to the parent’s height.
    • If the parent has no defined height, height: 100% won’t work.
  2. Set all ancestor elements’ heights to 100%, starting from html and body.
  3. Use box-sizing: border-box to include padding and borders inside your height/width: *, *::before, *::after { box-sizing: border-box; }

🌐 Alternative: Use Viewport Units

A more modern and reliable approach is using viewport units:

.full-screen {
  width: 100vw;
  height: 100vh;
}
  • 100vw = 100% of the viewport width
  • 100vh = 100% of the viewport height

This method doesn’t depend on parent elements and is ideal for full-screen sections like hero banners or modals.


💡 Bonus: Use with Flexbox or Grid

Want to center content inside a full-screen container?

.full-screen {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

This gives you a full-screen layout with perfectly centered content.


✅ Summary

Giving an element 100% height and width in CSS is straightforward, but requires:

  • Setting the parent’s height for percentage-based sizing
  • Using html, body { height: 100%; } for full-page layouts
  • Considering viewport units (vh, vw) for simpler, more predictable behavior
Sharing Is Caring:

Leave a Comment