等宽取决于宽度?

时间:2017-04-09 19:32:47

标签: html css

如何显示不同数量的div?例如,第一部分有三个div,第二部分有两个。

但它们需要具有相同的宽度 - 所以div总是填充该部分,无论有多少div。

DIV - DIV - DIV
DIV --------- DIV

我想我需要使用最大宽度?是对的吗?

section {
  width: 960px;
  background: grey;
}

div {
  display: inline-block;
  margin: 0;
  height: 200px;
  background: black;
  width: 33%;
}
<section>
<div></div>
<div></div>
<div></div>
</section>

<section>
<div></div>
<div></div>
</section>

3 个答案:

答案 0 :(得分:2)

&#13;
&#13;
section {
  width: 960px;
  background: grey;
display: flex;
}

div {
  display: inline-block;
  height: 200px;
  background: black;
flex: 1 1 auto;
margin: 0 1rem;
}
&#13;
<section>
<div></div>
<div></div>
<div></div>
</section>

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

答案 1 :(得分:2)

您可以在父级上使用display: table,在子级上使用display: table-cell

section {
  display: table;
  margin: 0 0 1em;
  width: 100%;
}
section > div {
  display: table-cell;
  background: #eee;
  border: 1px solid #aaa;
  height: 1em;
}
<section>
  <div></div>
  <div></div>
  <div></div>
</section>

<section>
  <div></div>
  <div></div>
</section>

答案 2 :(得分:1)

如果设置了wrap,则

flex将通过flex从单个部分完美地管理这个,并且min-width来调整每行上的div的最大数量

section {
  width: 960px;
  background: grey;
  display:flex;
  flex-wrap:wrap;
  justify-content:space-between;
  padding:3px;/* equals, to fit children margins value */
}

div {
  display: inline-block;
  margin:3px ;
  height: 200px;/* can be be min-height or removed to let tallest div to set row's height */
  background: black;
  min-width: 32%;
  flex:1;
}
.ha div {
height : auto;
color:white;
padding:1em;
}
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>
<hr/>
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>
<hr/>
<section class="ha">
<div> hi <i>(let's height be)</i></div>
<div> the<br/>world</div>
</section>