CSS - 为什么不百分比高度工作? [英] CSS – why doesn’t percentage height work?
问题描述
height
的百分比值无效,但是 width
的百分比值是多少?
例如:
< pre class =lang-html prettyprint-override>
< div id =working>< / div>
< div id =not-working>< / div>
#working {
width:80%;
height:140px;
background:orange;
}
#not-working {
width:80%;
height:30%;
background:green;
}
#working
最终为视口的80%,但#not-working
的高度最终为0.
块元素的高度默认为块内容的高度。所以,给定这样的:
< div id =outer>
< div id =inner>
< p>煎饼房子在哪里?< / p>
< / div>
< / div>
#inner
以包含段落,并且 #outer
将增长到足够高以包含 #inner
。
当您以百分比形式指定高度或宽度时,这是相对于元素父级的百分比。在width的情况下,除非另有说明,否则所有块元素都与它们的父代一样宽,直到< html>
;因此,块元素的宽度与其内容无关,并且 width:50%
产生明确定义的像素数。
但是,除非指定特定高度,否则块元素的高度取决于其内容。因此,在父级和子级之间有高度相关的反馈,并且 height:50%
不会产生明确定义的值,除非您通过给予父级元素的特定高度。
How come a percentage value for height
doesn’t work but a percentage value for width
does?
<div id="working"></div>
<div id="not-working"></div>
#working{
width:80%;
height:140px;
background:orange;
}
#not-working{
width:80%;
height:30%;
background:green;
}
The width of #working
ends up being 80% of the viewport, but the height of #not-working
ends up being 0.
The height of a block element defaults to the height of the block's content. So, given something like this:
<div id="outer">
<div id="inner">
<p>Where is pancakes house?</p>
</div>
</div>
#inner
will grow to be tall enough to contain the paragraph and #outer
will grow to be tall enough to contain #inner
.
When you specify the height or width as a percentage, that's a percentage with respect to the element's parent. In the case of width, all block elements are, unless specified otherwise, as wide as their parent all the way back up to <html>
; so, the width of a block element is independent of its content and saying width: 50%
yields a well defined number of pixels.
However, the height of a block element depends on its content unless you specify a specific height. So there is feedback between the parent and child where height is concerned and saying height: 50%
doesn't yield a well defined value unless you break the feedback loop by giving the parent element a specific height.
这篇关于CSS - 为什么不百分比高度工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!