CSS Flex动态填充可用高度(无高度或位置)

时间:2015-03-31 17:38:19

标签: css flexbox

如何在不指定heightposition(静态)属性的情况下使CSS Flex动态填充可用高度?

在下面的XHTML代码中,我需要浅蓝色框将空格填充到浅红色元素。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Flex Vertical Fill Test</title>
<style type="text/css">
#e1, #e2 {float: left; width: 50%;}
#e1 {background-color: #cff;}
#e2 {background-color: #ffc;}
#e3 {background-color: #fcf; clear: both;}
</style>
</head>

<body>

<div id="e1">
<div><p>Needs to use full available height.</p></div>
</div>

<div id="e2">
<p>Automatically generates height from content.</p>
<p>Automatically generates height from content.</p>
<p>Automatically generates height from content.</p>
<p>Automatically generates height from content.</p>
</div>

<div id="e3"><p>Natural content below</p></div>

</body>
</html>

我在Firefox 首先,然后是Chrome和IE。

进行测试

2 个答案:

答案 0 :(得分:1)

为了让它发挥作用,我为e1e2添加了一个容器。

<div id="e1-e2">
    <div id="e1">
        <p>Needs to use full available height.</p>
    </div>
    <div id="e2">
        <p>Automatically generates height from content.</p>
        <p>Automatically generates height from content.</p>
        <p>Automatically generates height from content.</p>
        <p>Automatically generates height from content.</p>
    </div>
</div>
<div id="e3">
    <p>Natural content below</p>
</div>

选项1:使用tabletable-cell(推荐)。

#e1-e2 {
    display: table;
}
#e1, #e2 {
    display: table-cell;
    width: 50%;
}

演示:http://jsfiddle.net/qnz7mao6/


选项2:使用flexbox

#e1-e2 {
    display: flex;
}
#e1, #e2 {
    width: 50%;
}

演示:http://jsfiddle.net/86n04amt/


选项3:如果您仍然喜欢float布局。

#e1-e2 {
    overflow: hidden;
}
#e1, #e2 {
    float: left;
    width: 50%;
}
#e1 {
    background-color: #cff;
    padding-bottom: 1000px;
    margin-bottom: -1000px;
}

演示:http://jsfiddle.net/11k8hds9/


提示:对padding使用margin代替<p>,以避免不必要的差距。

答案 1 :(得分:0)

好的我可以在纯css中给出一些解决方案,但是使用js是正确的。

这是html部分

<div class="container">
    <div class="fake-bg"></div>
    <div class="fake-bg"></div>
    <div id="e1"><p>Needs to use full available height.</p></div>
    <div id="e2">
        <p>Automatically generates height from content.</p>
        <p>Automatically generates height from content.</p>
        <p>Automatically generates height from content.</p>
        <p>Automatically generates height from content.</p>
    </div>
    <div class="clear"></div>
</div>

<div id="e3"><p>Natural content below</p></div>

和css paert

.container {
    position: relative;
}
.clear {
    clear: both;
}
.fake-bg {
    height: 100%;
    position: absolute;
    width: 50%;
    z-index: -1;
}

.fake-bg:nth-of-type(1) {
    background-color: #cff;
    left: 0;
    top: 0;
}
.fake-bg:nth-of-type(2) {
    background-color: #ffc;
    right: 0;
    top: 0;
}

#e1, #e2 {float: left; width: 50%;}
#e1 {background-color: #cff;}
#e2 {background-color: #ffc;}
#e3 {background-color: #fcf; clear: both;}

jsfiddle示例

enter link description here