首页 文章

如何在中心有两个固定宽度的列和一个柔性列?

提问于
浏览
253

我正在尝试设置一个包含三列的flexbox布局,其中左列和右列具有固定宽度,中心列弯曲以填充可用空间 .

尽管为列设置了尺寸,但随着窗口缩小,它们似乎仍在缩小 .

有谁知道怎么做到这一点?

我需要做的另一件事是根据用户交互隐藏右列,在这种情况下,左列仍将保持其固定宽度,但中间列将填充剩余的空间 .

#container {
    display: flex;
    justify-content: space-around;
    align-items: stretch;
    max-width: 1200px;
}

.column.left {
    width: 230px;
}

.column.right {
    width: 230px;
    border-left: 1px solid #eee;
}

.column.center {
    border-left: 1px solid #eee;
}
<div id="container">
    <div class="column left">
        <p>Anxiety was a blog series that ran in the New York Times Opinion section from January 2012 to July 2013. It featured essays, fiction, and art by a wide range of contributors that explored anxiety from scientific, literary, and artistic perspectives.</p>
    </div>
    <div class="column center">
        <img src="http://i.imgur.com/60PVLis.png" width="100" height="100" alt="">
    </div>
    <div class="column right">
        Balint Zsako
        
Someone’s Knocking at My Door
01.12.13 </div> </div>

这是一个JSFiddle:http://jsfiddle.net/zDd2g/185/

3 回答

  • 41

    而不是使用 width (这是使用flexbox时的建议),您可以使用 flex: 0 0 230px; ,这意味着:

    • 0 =不成长( flex-grow 的简写)

    • 0 =不收缩( flex-shrink 的简写)

    • 230px =从 230px 开始( flex-basis 的简写)

    这意味着:永远是 230px .

    See fiddle,谢谢@TylerH

    哦,你不需要 justify-contentalign-items .

  • 509

    尽管为柱子设置尺寸,但随着窗口缩小,它们似乎仍然缩小 .

    Flex容器的初始设置为flex-shrink: 1 . 这就是你的专栏缩小的原因 .

    无论您指定的宽度(it could be width: 10000px)都无关紧要,使用 flex-shrink 可以忽略指定的宽度,并防止弹性项溢出容器 .

    我正在尝试设置一个带有3列的弹箱,其中左右列具有固定的宽度......

    您需要禁用收缩 . 以下是一些选项:

    .left, .right {
         width: 230px;
         flex-shrink: 0;
     }
    

    要么

    .left, .right {
         flex-basis: 230px;
         flex-shrink: 0;
    }
    

    或者,根据规范的建议:

    .left, .right {
        flex: 0 0 230px;    /* don't grow, don't shrink, stay fixed at 230px */
    }
    

    7.2 . 灵活性组件鼓励作者使用flex速记来控制灵活性,而不是直接使用其纵向属性,因为速记正确地重置任何未指定的组件以适应常见用途 .

    更多细节:What are the differences between flex-basis and width?

    我需要做的另一件事是根据用户交互隐藏右列,在这种情况下,左列仍将保持其固定宽度,但中间列将填充剩余的空间 .

    试试这个:

    .center { flex: 1; }
    

    这将允许中心列消耗可用空间,包括删除它们的兄弟姐妹的空间 .

    Revised Fiddle

  • 0

    与旧版浏览器的兼容性可能会拖累,因此请注意 .

    如果这不是问题,那就继续吧 . 运行代码段 . 转到整页视图并调整大小 . 中心将自行调整大小,不会更改左或右div .

    更改左右值以满足您的要求 .

    谢谢 .

    希望这可以帮助 .

    #container {
      display: flex;
    }
    
    .column.left {
      width: 100px;
      flex: 0 0 100px;
    }
    
    .column.right {
      width: 100px;
      flex: 0 0 100px;
    }
    
    .column.center {
      flex: 1;
      text-align: center;
    }
    
    .column.left,
    .column.right {
      background: orange;
      text-align: center;
    }
    
    <div id="container">
      <div class="column left">this is left</div>
      <div class="column center">this is center</div>
      <div class="column right">this is right</div>
    </div>
    

相关问题