Height: 100% 还是 min-height: 100% 用于 html 和 body 元素?

在设计布局时,我将 html, body元素的 height设置为 100%,但是在某些情况下,这会失败,那么应该使用什么呢?

html, body {
height: 100%;
}

或者

html, body {
min-height: 100%;
}

好吧,这并不是基于观点,因为每种方法都有自己的缺陷,那么推荐的方法是什么呢? 为什么呢?

77267 次浏览

If you're trying to apply background images to html and body that fill up the entire browser window, neither. Use this instead:

html {
height: 100%;
}


body {
min-height: 100%;
}

My reasoning is given here (where I explain holistically how to apply backgrounds in this manner):

Incidentally, the reason why you have to specify height and min-height to html and body respectively is because neither element has any intrinsic height. Both are height: auto by default. It is the viewport that has 100% height, so height: 100% is taken from the viewport, then applied to body as a minimum to allow for scrolling of content.

The first way, using height: 100% on both, prevents body from expanding with its contents once they start to grow beyond the viewport height. Technically this doesn't prevent the content from scrolling, but it does cause body to leave a gap beneath the fold, which is usually undesirable.

The second way, using min-height: 100% on both, doesn't cause body to expand to the full height of html because min-height with a percentage doesn't work on body unless html has an explicit height.

For the sake of completeness, section 10 of CSS2.1 contains all the details, but it's an extremely convoluted read so you can skip it if you're not interested in anything beyond what I've explained here.

You can use viewport height (vh) unit:

body {
min-height: 100vh;
}

It is relative to screen, not to parent height, so you don't need html height: 100%.