是否可以在创建后计算divs宽度?

Mar*_*ver 2 html css css3

我有一些div用PHP生成的s,我希望divs 的宽度是偶数(即2 = 50%,3 = 33%,4 = 25%等),无论有多少divs.

我想用CSS做到这一点,有可能吗?

.container {
  margin: 10px 0;
  width: 100%;
}
.container div {
  height: 50px;
}
.container div:nth-child(odd) {
  background-color: red;
}
.container div:nth-child(even) {
  background-color: blue;
}
.twoColumns,
.threeColumns,
.fourColumns {
  height: 50px;
}
.twoColumns div,
.threeColumns div,
.fourColumns div {
  float: left;
}
.twoColumns div {
  width: 50%;
}
.threeColumns div {
  width: 33.333333333%;
}
.fourColumns div {
  width: 25%;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <h1>Example markup</h1>
  <strong>This would be two columns:</strong>
  <div class="container">
    <div></div>
    <div></div>
  </div>
  <strong>This would be three columns:</strong>
  <div class="container">
    <div></div>
    <div></div>
    <div></div>
  </div>
  <strong>This would be four columns:</strong>
  <div class="container">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
</div>
<div>
  <h1>Desired result (using set widths)</h1>
  <strong>This is two columns:</strong>
  <div class="container twoColumns">
    <div></div>
    <div></div>
  </div>
  <strong>This is three columns:</strong>
  <div class="container threeColumns">
    <div></div>
    <div></div>
    <div></div>
  </div>
  <strong>This is four columns:</strong>
  <div class="container fourColumns">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Hid*_*bes 7

Flexbox可用于使元素具有相同的宽度:

  • 添加display: flex;到contains元素以使其所有子元素都使用flexbox模型
  • 添加flex: 1;到子元素以允许它们根据需要拉伸/收缩

.container {
  display: flex;
  height: 100px;
  margin: 10px 0;
  width: 100%;
}
.container div {
  flex: 1;
}
.container div:nth-child(odd) {
  background-color: red;
}
.container div:nth-child(even) {
  background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
Run Code Online (Sandbox Code Playgroud)