user6395724 user6395724 - 3 months ago 11
CSS Question

css fill height of screen when window is zoomed 100%

How do you fill the height when the website is zoomed 100%? When zoomed out i don't want the element to keep filling the screen. To be more clear, when a user enters the website and the website is zoomed by the default 100% the whole screen should be filled with a color. But when the user scrolls down or zooms the fill should not dynamically change its height.

From comments i edit the code to get a better result, but now there is gaps around the element:

header.mainHeader {
background-color: #282828;
width: 100%;
height: 100vh;
box-sizing: border-box;
}

Answer

First, you're setting the position: fixed of the .mainHeader class. This causes the element to always be at the same position in the viewport, regardless of zoom-level or scrolling position.

Remove this position: fixed, and its corresponding top and left properties.


You're currently setting the height to 100% of its parent element, so it would always be as big as that.

To set the height using the viewport's (visible page area) height, you can use vh units, equivalent to percentage of the viewport height (vh) - likewise for width and vw.

So, to set the height of the element to 100% of the viewport height, you can simply do:

height: 100vh;

EDIT - NOTE: the vh unit isn't supported by all browsers (I've found some, trust me). So I would recommend setting a fallback value, above the vh one, to prevent incompatibility. For example:

height: 500px; // fallback value if browser doesn't support vh
height: 100vh; // this value overrides the above one, if the browser supports vh

You might then need to remove padding and/or margin from the body or other elements, if you're seeing whitespace around the element. Have a play about to get the right effect.

For example:

body {
  padding: 0;
  margin: 0;
  ... other properties
}

Please find a JSFiddle of this in action: https://jsfiddle.net/s49p6Laj/

Sample code:

HTML

<div class="header">
  I fill the viewport!
</div>
<div class="other-stuff">
  // All your other content here...
</div>

CSS

// Set the body's margin and padding to 0
body {
  margin: 0;
  padding: 0;
}

// Make the container fill the viewport
.header{
  width: 100%;
  height: 100vh;
Comments