height: 100% 或 min-height: 100% 用于 html 和 body 元素? [英] height: 100% or min-height: 100% for html and body elements?
问题描述
在设计布局时,我将 html, body
元素的 height
设置为 100%
但在某些情况下,这会失败,那该怎么办用吗?
While designing layouts I set the html, body
elements' height
to 100%
but in some cases, this fails, so what should be used?
html, body {
height: 100%;
}
或
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?
推荐答案
如果您尝试将背景图像应用于填充整个浏览器的 html
和 body
窗户,也没有.改用这个:
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):
顺便说一下,你必须分别指定 height
和 min-height
到 html
和 body
的原因是因为这两个元素都没有任何固有高度.默认情况下,两者都是 height: auto
.它是具有 100% 高度的视口,因此 height: 100%
取自视口,然后应用到 body
作为最低限度,以允许滚动内容.
Incidentally, the reason why you have to specify
height
andmin-height
tohtml
andbody
respectively is because neither element has any intrinsic height. Both areheight: auto
by default. It is the viewport that has 100% height, soheight: 100%
is taken from the viewport, then applied tobody
as a minimum to allow for scrolling of content.
第一种方法,在两者上使用 height: 100%
,防止 body
在内容开始增长超过视口高度时随其内容扩展.从技术上讲,这不会阻止内容滚动,但会导致 body
在折叠下方留下间隙,这通常是不可取的.
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.
第二种方式,在两者上使用 min-height: 100%
,不会导致 body
扩展到 html
因为带有百分比的 min-height
对 body
不起作用,除非 html
有明确的 height
.
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
.
为了完整起见,第 10 节 CSS2.1 包含所有详细信息,但这是一个极其令人费解的阅读,因此如果您对我在此处解释的内容之外的任何内容不感兴趣,可以跳过它.
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.
这篇关于height: 100% 或 min-height: 100% 用于 html 和 body 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!