简体   繁体   中英

Why is this div with 100vh height not covering the whole viewport?

The blue div in this code has a height of 100vh whereas the red div has the height of 5000px. Shouldn't the blue div extend itself to cover the whole viewport because of the 100vh height attribute?

 body { margin: 0; } 
 <div style="position: absolute; left: 35%; width: 100px; height: 100vh; background-color: blue;"> </div> <div style="position: absolute; left: 50%; width: 100px; height: 5000px; background-color: red;"></div> 

What I want to achieve from this is that suppose there's some text which overflows on sizing down the window then how should I get around that situation so that the 100vh height div again covers up the new window size?

Viewport height just means that the height of the element will be a percentage of the viewport. The viewport being the window your viewing the page on. So if it is a 1920x1080 screen the viewport height will be 1080px or whatever your browser window is, it may be less if you have a toolbar at the bottom of your screen. The issue you are having is that if you want the sidebar to follow the main content down the page you need to disregard the viewport and have a wrapper around both of them like so:

 .main-wrapper{ display:flex; } aside{ background:blue; color:#fff; width:200px; } main{ background:green; height:5000px; flex:1 } 
 <div class="main-wrapper"> <aside>Your sidebar</aside> <main>Your Main Content</main> </div> 

That being said you may want to check out the following fiddle Here . I have made this fiddle responsive for mobile screens so you may have to resize the output window larger to view the sidebar layout. The issue is you are absolutely positioning items and fixing items outside divs which is bad practice. In your example you commented on above you have many layout and z-index issues that you will run into. This fiddle is just an example but it should give you a good frame of reference on how the layout should be thought of.

It is happening because that's how vh works. vh is based on the height of viewport. 1vh = 1% of viewport height.

https://www.sitepoint.com/css-viewport-units-quick-start/

1vh is Relative to 1% of the height of the viewport*

so 100vh will correspond to 100% of the height of the viewport

demo here

For further details please refer to the CSS Units documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM