CSS 横向n等分

477 阅读1分钟

在一个父div内平均放置n个子div,子div充满父级,不换行.

  <div id="father">
    <div class="children"></div>
    <div class="children"></div>
    <div class="children"></div>
    <div class="children"></div>
    <div class="children"></div>
    <div class="children"></div>
    <div class="children"></div>
    <div class="children"></div>
  </div>

1.已知n的个数,直接设置子宽度等于父的1/n

2.table表格

  需要在外层再套个div(grandfather).最好是两个以上的children.
父级设置为行,children设置为行内元素,父级的宽度不再可设置.父级的border也不显示.children宽度设置为 [granfanther/2 - granfather] (不是最大宽度).当最外层(grandfather)宽度变化时,children会自适应变化.
  当所有children的宽度和 小于grandfather宽度时,children会左对齐,右侧留出空白,不再是等分效果.

#father{
    display: table-row;
}
.children{
    border: 1px solid black;
    width: 900px;
    height: 20px;
    display: table-cell;
}

效果:

3.flax布局

#father{
    width:400px;
    padding: 2px;
    border: 1px dotted red;
    display: flex;
}
.children{
    border: 1px solid black;
    height: 20px;
    flex: 1;
}

效果: