如何使用flex有比例列?

时间:2018-07-11 14:03:58

标签: css flexbox

我正在学习flexbox。

我正在尝试在单行上使元素按比例固定为1:2的比例。

.cell {
  padding: 8px 16px;
}

.cell > div {
  height: 30px;
}

.row {
  display: flex;
}
<div class="row">
   <div class="cell" style="flex: 1"><div style="background: red"></div></div>
   <div class="cell" style="flex: 1"><div style="background: blue"></div></div>
   <div class="cell" style="flex: 1"><div style="background: yellow"></div></div>
</div>
<div class="row">
   <div class="cell" style="flex: 1"><div style="background: green"></div></div>
   <div class="cell" style="flex: 2"><div style="background: purple"></div></div>
</div>

为什么flex属性无法达到目的?

这可以通过flexbox实现吗? (可以通过其他方式实现,但我正在学习flexbox的工作方式。)

1 个答案:

答案 0 :(得分:1)

.cell中删除填充,并在单元格(.cell>div)中的div中添加边距

.cell>div {
  height: 30px;
  margin: 8px 16px;
}

.cell>div {
  height: 30px;
  margin: 8px 16px;
}

.row {
  display: -webkit-box;
  /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box;
  /* OLD - Firefox 19- (buggy but mostly works) */
  display: -ms-flexbox;
  /* TWEENER - IE 10 */
  display: -webkit-flex;
  /* NEW - Chrome */
  display: flex;
}
<div class="row">
  <div class="cell" style="flex-grow: 1;flex-shrink: 1;flex-basis: 0%;">
    <div style="background: red"></div>
  </div>
  <div class="cell" style="flex-grow: 1;flex-shrink: 1;flex-basis: 0%;">
    <div style="background: blue"></div>
  </div>
  <div class="cell" style="flex-grow: 1;flex-shrink: 1;flex-basis: 0%;">
    <div style="background: yellow"></div>
  </div>
</div>
<div class="row">
  <div class="cell" style="flex-grow: 1;flex-shrink: 1;flex-basis: 0%;">
    <div style="background: green"></div>
  </div>
  <div class="cell" style="flex-grow: 2;flex-shrink: 1;flex-basis: 0%;">
    <div style="background: purple"></div>
  </div>
</div>