简体   繁体   中英

Body not 100% height but 100% Viewport

https://jsfiddle.net/nprq5LLo/

Simple project I started working on , problem is that the body isnt 100% height of the document, its 100% of the viewport. Which is an issue since I want to use full-screen elements in future for it.

  html {
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
  position: relative;
}

body {
  background-size: 100% 100%;
  background-color: #000;
  color: white;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
  position: relative;
}

having html and body defined with 100% width and height and removing padding and margin did nothing to resolve the issue , i ran thru this type of questions in stackoverflow but none of the solutions were usefull for me.

I've tried adding lorems to make the page scrollable ,but the actual height of the body is as much as the viewport is , the content below is visible though.

Any ideas how we can solve this issue?

If you want to make sure your height is at least 100% but then it grows with content, then instead of using height: 100% you should use min-height: 100% .

However, on your example, you may wonder why even if there's no enough content you still get a vertical scroll bar. That's because the h1 's margin-top is displacing the parent and making your body not start at the very top but rather at 0.67em (which is the h1's top margin on, for example, Google Chrome's User Agent by default).

There are many ways to solve this. You can:

  • add a padding-top: 1px to the .header . If you want to be pixel perfect you can also add margin-top: -1px .
  • add overflow: auto to the .header .
  • remove the margin-top of the h1 if you don't need it

Here's an implementation that uses min-height: 100% on body and also uses overflow: auto on the .header . See how the body takes at least 100% of the height of the viewport, or its content's height if it's bigger than 100%. https://jsfiddle.net/nprq5LLo/7/

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