我有一个非常简单的结构:
<div class="parent">
<h1>Element taking space</h1>
<div class="stretch">
Not much content, but needs to be stretched to the end.
</div>
</div>
父div
有一个固定的高度,我想让div.stretch
一直延伸到那个高度,不管它的内容有多少。使用height: 100%
的伎俩,直到你添加一些其他的元素,推动内容向下。
我猜指定height: 100%
意味着元素应该具有与父元素完全相同的绝对/计算高度,而不是在所有其他元素计算后的剩余高度。
设置overflow: hidden
显然隐藏了溢出的内容,但这不是我的选择。
在纯CSS中有什么方法可以实现吗?
演示我的问题
自从这个问题被提出和回答之后,一种更好的方法出现了:flex-box。
只需将父元素的显示设置为"flex",flex-direction设置为"column",并将"stretchy"子元素的高度设置为"inherit"。子元素将继承其父元素剩余的高度。
在以下示例中,标记为/* important */的行是实际解决方案的一部分;CSS的其余部分只是为了让它在视觉上更容易理解。
.parent {
display: flex; /* important */
flex-direction: column; /* important */
height: 150px;
border: 6px solid green;
}
h1 {
background: blue;
margin: 0px;
height: 90px
}
.stretch {
background: red;
height: inherit; /* important */
}
<div class="parent">
<h1>Element taking space</h1>
<div class="stretch">
Not much content, but needs to be stretched to the end.
</div>
</div>
可以浮动h1元素。无论它的高度是多少,它都可以工作,并且拉伸元素的内容将被推到它的下方。但我不完全确定这是否是你要找的。
EDIT:我不确定你在寻找什么样的浏览器支持,但你也可以将.parent
上的显示设置为table
,然后将.stretch
inherit
设置为高度。然后你可以在.stretch
内嵌套列div并浮动它们。
更新strong>: http://jsbin.com/oluyin/2/edit