2014-03-19 26 views
1

我有一个div结构这样,为什么股利不走剩余空间

<div style="height:100%"> 
    <div style="height:50px"></div> 
    <div id="auto" style="height:100%"></div> 
</div> 

但好像id="auto"走的是高度为其父身高和父溢出。可以设置css的方式0123'div取父母的剩余高度? 我想要做的是让id=auto股利承担母公司div大小的其余部分。

这里是jsFiddle

回答

2

这是因为height属性的百分比值是相对于包含框的块的高度而言的。因此100%意味着整个高度。

10.5 Content height: the 'height' property

指定的百分比高度。百分比的计算方法为 尊重所生成框的高度containing block。如果未明确指定包含块的高度 (即,其 取决于内容高度),并且该元素不是绝对 定位,则该值计算为'auto'。 root element上的百分比高度相对于initial containing block

一个解决办法是使用负余量为第二<div>元件以除去srcollbar,然后加入position: relative;到第一个,使其回到在第二一个的顶部。

在这种情况下,我们应该使用padding第二DIV的顶部,以推动其内容下来,也是为了增加box-sizing: border-box计算包括填充边界框的高度:

Example Here

<div class="parent"> 
    <div class="top"></div> 
    <div class="content"></div> 
</div> 
.parent { height:100%; } 

.top { 
    height: 100px; 
    position: relative; 
} 

.content { 
    background-color: gold; 
    min-height: 100%; 

    margin-top: -100px; /* equals to the height of .top element */ 
    padding-top: 100px; /* equals to the height of .top element */ 

    -webkit-box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    box-sizing: border-box; 
} 

值得注意的是,这种方法would work on IE8+


时下所有主流浏览器都支持box-sizing: border-box,但是你用隔离元件代替padding + box-sizing.content下的内容:

Example Here

<div class="content"> 
    <div class="spacer"></div> 
    <!-- content goes here -->. 
</div> 
.spacer, .top { 
    height: 100px; 
} 

这种方法将上工作IE 6/7 +(*)


或者,也可以嵌套在.content.top元件和丢弃.parent在为了达到同样的效果正在处理中IE 6/7 +(*)

Example Here

<div class="content"> 
    <div class="top"></div> 
    <div class="inner"> 
     <!-- content goes here --> 
    </div> 
</div> 

(*)IE6 +通过使用height属性,IE7 +通过使用min-height

1

如果您不需要支持IE8或IE9,使用CSS钙(http://caniuse.com/calc

<div style="height:100%"> 
    <div style="height:50px"></div> 
    <div id="auto" style="height:calc(100%-50px);"></div> 
</div> 

如果你需要支持旧的IE浏览器的话,我会建议使用display:table,display:table-cell和display:table-row。使用桌面显示器时要记住很多小怪癖,所以如果可能的话,坚持使用calc。

1

可以达到预期的效果,如果你能绝对定位的第一个孩子的div(一个是100个像素高):

演示:http://jsfiddle.net/rn2Xe/2/

<div style="height:100%; padding-top:100px; box-sizing: border-box; position: relative;"> 
    <div style="height:100px; position: absolute; top: 0; width: 100%; box-sizing: border-box;"></div> 
    <div style="height:100%;"></div> 
</div> 

注意:使用类CSS 。你的代码可能是很多更清洁。

1

你也许可以用css calc来解决这个问题,但是如果你想要很好的遗留支持,可以使用表格。