如何使自动调节DIV宽度达到100%?

时间:2018-04-20 12:14:49

标签: html css

我有一个包含动态生成的DIV的页面。 那些DIV被放在另一个父母的内部" DIV(class="container")。我需要显示每行宽度相等的2个DIV(现在是940px,这是宽度的100%)。

但有时DIV内容很长,而且需要更多空间。所以我不能将宽度限制为固定的数字。我只使用min-width: 460px;

如果我在最后一行留下了一个DIV(可能会发生),我需要将这个DIV一直延伸到960px(100%)。而且这种情况并不总是一样的。有时只有一个DIV,有时两个(在页面的末尾)。而且我需要CSS来理解":如果在DIV之后有一个空格,DIV应该被拉伸到全宽(960px),如果右边有另一个DIV,那么两个DIV应该是480px并在同一行。

我也尝试了:last-child,但它对我不起作用。

要查看代码中的摘要,请参阅我的小清单:

<style>
    .container {
        width: 960px;
    }
    .content {
        float: left;
        min-width: 480px;
    }
</style>

<div class="container">
    <div class="content" style="background-color: Orchid;">Hi! I am content</div>
    <div class="content" style="background-color: NavajoWhite;">Hi! I am content</div>
    <div class="content" style="background-color: Chartreuse;">Hi! I am content.. Very loooong-loooong content.. Too many words. Too many.. More and more and more... And even more for you! Believe me, I will grab all 100% of the container DIV</div>
    <div class="content" style="background-color: Aquamarine;">Hi! I am a last content</div>
</div>

谢谢。

1 个答案:

答案 0 :(得分:1)

使用flexbox:

&#13;
&#13;
.container {
  margin-bottom:20px;
  width: 960px;
  display: flex;
  flex-wrap: wrap;
}

.content {
 /* flex-basis: 50%; // in my case it was odd */
  flex-grow: 1;
}
&#13;
<div class="container">
  <div class="content" style="background-color: NavajoWhite;">Hi! I am content</div>
  <div class="content" style="background-color: Chartreuse;">Hi! I am content.. Very loooong-loooong content.. Too many words. Too many.. More and more and more... And even more for you! Believe me, I will grab all 100% of the container DIV</div>
  <div class="content" style="background-color: Aquamarine;">Hi! I am a last content</div>

</div>
<div class="container">
  <div class="content" style="background-color: NavajoWhite;">Hi! I am content</div>
  <div class="content" style="background-color: Chartreuse;">Hi! I am content.. Very loooong-loooong content.. Too many words. Too many.. More and more and more... And even more for you! Believe me, I will grab all 100% of the container DIV</div>
  <div class="content" style="background-color: Aquamarine;">Hi! I am a last content</div>
  <div class="content" style="background-color: orange;">Hi! I am a last content</div>

</div>
&#13;
&#13;
&#13;