首页 > 解决方案 > 如何使用 flex 拥有比例列?

问题描述

我正在学习弹性盒子。

我正在尝试在单行上制作按固定 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 的工作原理。)

标签: cssflexbox

解决方案


从单元格 ( ).cell内的 div 中删除填充并添加边距.cell>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>


推荐阅读