代码之家  ›  专栏  ›  技术社区  ›  Paul Draper

如何使用flex设置比例列?

  •  1
  • Paul Draper  · 技术社区  · 6 年前

    我在学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 回复  |  直到 6 年前
        1
  •  1
  •   Nandita Sharma    6 年前

    从上拆下衬垫 .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>