如何使未知数量的div平等地填充所有剩余空间?

时间:2018-10-10 17:17:47

标签: javascript html css

我想获得下一个结果:

.container{
  width: 100vw;
  height: 40vh;
  display: flex;
  background-color: gray;
}
.a{
  background-color: red;
}
.b{
  background-color: blue;
}
.right > *{
  width: 50%
}
<p>Problem</p>
<div class="wrong container">
  <div class="a">text</div>
  <div class="b">text</div>
</div>
<p>Expected</p>
<div class="right container">
  <div class="a">text</div>
  <div class="b">text</div>
</div>

如果我们知道容器内的元素数量,很明显我们可以手动设置子元素的宽度。但是,如果我们不知道孩子的数量,但我们希望他们以所有孩子相等的宽度来填充父母所有可用的宽度,该怎么办?

3 个答案:

答案 0 :(得分:1)

我刚刚在每个div元素中添加了flex: 1

查看这篇文章:a complete guide to flexbox

TLDR:

  

这是flex-grow,flex-shrink和flex-basis的简写   结合。第二和第三个参数(flex-shrink和flex-basis)   是可选的。默认值为0 1自动。

.container{
  width: 100vw;
  height: 40vh;
  display: flex;
  background-color: gray;
}
.item{
  flex: 1;
}
.a{
  background-color: red;
}
.b{
  background-color: blue;
}
.right > *{
  width: 50%
}
<p>Problem</p>
<div class="wrong container">
  <div class="a">text</div>
  <div class="b">text</div>
</div>
<p>Expected</p>
<div class="right container">
  <div class="a item">text</div>
  <div class="b item">text</div>
  <div class="C item">text</div>
</div>

答案 1 :(得分:1)

您可以使用flex。

  .container{
  width: 100vw;
 height: 40vh;
 display: flex;
background-color: gray;
display:flex
   }
  .container > div{
flex-grow: 1;
 }

.container{
  width: 100vw;
  height: 40vh;
  display: flex;
  background-color: gray;
  display:flex
}
.container > div{
  flex-grow: 1;
}
.a{
  background-color: red;
}
.b{
  background-color: blue;
}
.right > *{
  width: 50%
}
<p>Problem</p>
<div class="wrong container">
  <div class="a">text</div>
  <div class="b">text</div>
</div>
<p>Expected</p>
<div class="right container">
  <div class="a">text</div>
  <div class="b">text</div>
</div>

答案 2 :(得分:0)

<div class="card">
  <p>Lorem Ipsum is simply dummy text of the printing and typeset </p>
  <div class="avatar"></div>
</div>
<div class="card">
  <p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p>
  <div class="avatar"></div>
</div>

<div class="card">
  <p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p>
  <div class="avatar"></div>
</div>

将此添加到CSS。当然,这是一个粗略的解决方案。更好的方法是创建一个类,而不是将其应用于页面中的所有div。