【问题标题】:First-child full-width in FlexboxFlexbox 中的第一个孩子全角
【发布时间】:2017-06-06 22:55:26
【问题描述】:

如何将 flexbox 的第一个子元素设置为全角,而将所有其他子元素设置为 flex:1(用于分割空间)?

像这样:

【问题讨论】:

    标签: css flexbox


    【解决方案1】:

    您可以将:first-child 设置为100% 的宽度,并将其余子:not(:first-child) 设置为flex: 1

    要将它们放在多行上,请在容器上使用flex-wrap: wrap

    .container {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      background: #e2eaf4;
      padding: 10px;
    }
    
    .child {
      display: inline-block;
      font-family: "Open Sans", Arial;
      font-size: 20px;
      color: #FFF;
      text-align: center;
      background: #3794fe;
      border-radius: 6px;
      padding: 20px;
      margin: 12px;
    }
    
    .child:first-child {
      width: 100%;
    }
    
    .child:not(:first-child) {
      flex: 1;
    }
    <div class="container">
      <div class="child">Child</div>
      <div class="child">Child</div>
      <div class="child">Child</div>
    </div>

    【讨论】:

    • 完美解决方案
    【解决方案2】:

    另一种使用flex-basis 选项的解决方案(使用此格式flex: 1 1 100% 时的第三个值)。

    MDN link for flex-basis

    .flexContainer {
      display: flex;
      flex-wrap: wrap;
    }
    
    .item:first-child {
      flex: 1 1 100%;
      margin-bottom: 20px;
    }
    
    .item {
      flex: 1 1 40%;
      height: 50px;
      background-color: red;
      margin: 0 20px;
    }
    <div class="flexContainer">
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
    </div>

    【讨论】:

      【解决方案3】:

      为您的第一项添加width: 100%;flex: 1; 其他人。

      .flex {
        display: flex;
        flex-wrap: wrap;
      }
      
      .flex-item:not(:first-child) {
        flex: 1;
      }
      
      .flex-item:nth-child(1) {
        width: 100%;
      }
      
      /* Styles just for demo */
      .flex-item {
        background-color: #3794fe;
        margin: 10px;
        color: #fff;
        padding: 20px;
        border-radius: 5px;
      }
      <div class="flex">
        <div class="flex-item">
          Child
        </div>
        <div class="flex-item">
          Child
        </div>
        <div class="flex-item">
          Child
        </div>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-11
        • 2012-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多