【问题标题】:Flexbox: Why flex-grow doesn't work with fixed width sibling?Flexbox:为什么 flex-grow 不适用于固定宽度的兄弟?
【发布时间】:2014-04-30 20:27:28
【问题描述】:

LIVE DEMO

考虑以下 HTML 和 CSS:

<div class="wrapper">
  <div class="first">The CSS3 Flexible Box, or flexbox, is a layout mode providing for the arrangement .</div>
  <div class="second"></div>
</div>
<div class="wrapper">
  <div class="first"></div>
  <div class="second"></div>
</div>


.wrapper {
  display: flex;
  border: 1px solid black;
  width: 300px;
  height: 100px;
  margin-top: 30px;
}
.first {
  flex-grow: 1;
  background-color: #aaa;
}
.second {
  width: 80px;
  background-color: #ddd;
}

结果如下:

为什么第一个包装器不尊重.secondwidth: 80px

我如何使用 flexbox 解决这个问题?

PLAYGROUND HERE

【问题讨论】:

    标签: css flexbox


    【解决方案1】:

    你需要使用flex: 1;而不是flex-grow: 1;

    .first {
        flex: 1;
        background-color: #aaa;
    }
    

    Demo


    另外,我想指出,就 IE 而言,flexbox 支持并不好,所以如果有人对具有更多兼容选项的类似布局感兴趣,那么

    <div class="wrapper">
        <div class="second"></div>
        <div class="first"></div>
    </div>
    
    
    .wrapper {
        border: 1px solid black;
        width: 300px;
        height: 100px;
        margin-top: 30px;
    }
    
    .wrapper .first {
        background: red;
        height: 100%;
        margin-right: 80px;
    }
    
    .wrapper .second {
        height: 100%;
        width: 80px;
        float: right;
        background: blue;
    }
    

    Demo (注意我在DOM中交换了div的顺序)

    【讨论】:

    • flex-shrink:0 在第二个 div 上?
    • @Paulie_D 即使这样就足够了,但这会节省一个额外的属性:)
    猜你喜欢
    • 2019-01-31
    • 1970-01-01
    • 2020-02-21
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多