三个浮动的div扩展以填充容器宽度

时间:2014-12-12 15:58:52

标签: html css

我不认为这在纯CSS中是可行的。我在包装容器中有三个浮动元素,我希望三个中心的内容是其内容的宽度,并且这两个元素的任何一侧都要填充此元素左右的剩余间隙。

<style>
.wrap {
    width: 50%;
    height: 100px;
    background: green;
}
.cont {
    background: red;
    float: left;
    display: inline-block;
    height: 100px;
}
.c1, .c3 {
    background: blue;
    width: auto;
}
</style>



<div class="wrap">
    <div class="cont c1">&nbsp;</div>
    <div class="cont c2">content</div>
    <div class="cont c3">&nbsp;</div>
</div>

http://jsfiddle.net/6eLdboqw/1/

我意识到这在Javascript中是微不足道的,但我想知道是否有纯CSS解决方案。

2 个答案:

答案 0 :(得分:2)

您可以使用CSS表格完成此操作,中间div的宽度为1%,自动收缩&#39;:

&#13;
&#13;
.wrap {
  width: 400px;
  height: 100px;
  background: green;
  display: table;
}
.cont {
  background: red;
  display: table-cell;
  height: 100px;
}
.c1,
.c3 {
  background: blue;
  width: auto;
}
.c2 {
  width: 1%;
}
&#13;
<div class="wrap">
  <div class="cont c1">&nbsp;</div>
  <div class="cont c2">content</div>
  <div class="cont c3">&nbsp;</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以使用flexbox这样做。

以下是演示:http://jsfiddle.net/6eLdboqw/3/

.wrap {
    width: 400px;
    height: 100px;
    background: green;
    display: flex;
}

.c1, 
.c3
{
    flex: 1 1 auto;
}

.c2
{
    flex: 0 0 auto;
}

.cont {
    background: red;
    height: 100px;

}
.c1, .c3 {
    background: blue;
    width: auto;
}

flex是:flex-grow, flex-shrink, flex-basis的简写属性。 我们所做的是:.c1, .c3可能会增长和缩小,但.c2可能不会增长或缩小。