height: 100% 或 min-height: 100% 用于 html 和 body 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17555682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:55:41  来源:igfitidea点击:

height: 100% or min-height: 100% for html and body elements?

htmlcss

提问by Mr. Alien

While designing layouts I set the html, bodyelements' heightto 100%but in some cases, this fails, so what should be used?

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

html, body {
   height: 100%;
}

or

或者

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

Well, this is not opinion based as each method has its own flaws, so what's the recommended way to go for and why?

嗯,这不是基于意见的,因为每种方法都有自己的缺陷,那么推荐的方法是什么,为什么?

回答by BoltClock

If you're trying to apply background images to htmland bodythat fill up the entire browser window, neither. Use this instead:

如果您尝试将背景图像应用到htmlbody填满整个浏览器窗口,则两者都不是。改用这个:

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 heightand min-heightto htmland bodyrespectively is because neither element has any intrinsic height. Both are height: autoby default. It is the viewport that has 100% height, so height: 100%is taken from the viewport, then applied to bodyas a minimum to allow for scrolling of content.

顺便说一下,您必须分别指定heightmin-heighttohtml和to 的原因body是因为这两个元素都没有任何固有高度。两者都是height: auto默认的。它是具有 100% 高度的视口,因此height: 100%取自视口,然后应用到body最小以允许滚动内容。

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

第一种方法,height: 100%在两者上使用,body一旦它们开始增长超过视口高度,就阻止其内容扩展。从技术上讲,这不会阻止内容滚动,但会导致body在折叠下方留下间隙,这通常是不可取的。

The second way, using min-height: 100%on both, doesn't cause bodyto expand to the full height of htmlbecause min-heightwith a percentage doesn't work on bodyunless htmlhas an explicit height.

第二种方式,使用min-height: 100%两个,不会引起body扩展到全高html,因为min-height有个不上工作body,除非html有明确的height

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

为完整起见,CSS2.1 的第 10 节包含所有详细信息,但这是一篇极其复杂的读物,因此如果您对我在此处解释的内容之外的任何内容不感兴趣,可以跳过它。

回答by Damjan Pavlica

You can use viewport height (vh) unit:

您可以使用视口高度 ( vh) 单位:

body {
    min-height: 100vh;
}

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

它相对于屏幕,而不是父高度,因此您不需要 html height: 100%。