CSS – why doesn’t percentage height work?
This question already has an answer here:
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.
A percentage value in a height
property has a little complication, and the width
and height
properties actually behave differently to each other. Let me take you on a tour through the specs.
height
property:
Let's have a look at what CSS Snapshot 2010 spec says about height
:
The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (ie, it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'. A percentage height on the root element is relative to the initial containing block. Note: For absolutely positioned elements whose containing block is based on a block-level element, the percentage is calculated with respect to the height of the padding box of that element.
OK, let's take that apart step by step:
The percentage is calculated with respect to the height of the generated box's containing block.
What's a containing block? It's a bit complicated, but for a normal element in the default static
position, it's:
the nearest block container ancestor box
or in English, its parent box. (It's well worth knowing what it would be for fixed
and absolute
positions as well, but I'm ignoring that to keep this answer short.)
So take these two examples:
<div id="a" style="width: 100px; height: 200px; background-color: orange">
<div id="aa" style="width: 100px; height: 50%; background-color: blue"></div>
</div>
I think you just need to give it a parent container... even if that container's height is defined in percentage. This seams to work just fine: JSFiddle
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.wrapper {
width: 100%;
height: 100%;
}
.container {
width: 100%;
height: 50%;
}
链接地址: http://www.djcxy.com/p/30002.html
上一篇: CSS媒体查询:最大
下一篇: CSS - 为什么百分比高度不起作用?