【问题标题】:Equal divs depending on width?相等的div取决于宽度?
【发布时间】:2017-04-10 03:51:33
【问题描述】:

如何显示不同数量的 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>

【问题讨论】:

  • 你试过 max-width 了吗?我不清楚你的要求是什么,无论行上有多少 div,div 的宽度都相同或所有行都填充?
  • @GCyrillus 抱歉 - 是的,所有行都已填满
  • 所以 roberto 和 mickael 回答了你,如果设置了 wrap 和 min-width 以调整每行上的最大 div 数,flex 将通过 flex 从单个部分完美地管理这个;)
  • @GCyrillus Brilliant,是的,这正是我需要的!
  • 好的,我从我的评论中做了一个回答,让你看看这个想法是如何运作的。

标签: html css


【解决方案1】:

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

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

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

【讨论】:

    【解决方案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>

    【讨论】:

      【解决方案3】:

      如果设置了 wrap 和 min-width 以调整每行上的最大 div 数,flex 将通过 flex 从单个部分完美地管理这个

      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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-29
        • 1970-01-01
        • 2012-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-24
        相关资源
        最近更新 更多