Fixed width child is shrinking in flexbox [duplicate]

落爺英雄遲暮 提交于 2021-01-26 08:32:22

问题


I'm using display:flex for the first time.

You find a codepen here: https://codepen.io/chrispillen/pen/GEYpRg

.node:not(.branch) {
  width: auto;
  height: 100px;
  background: red;
  margin-bottom: 1px;
}

.node.branch,
.node.branch .body {
  width: auto;
  overflow: hidden;
}

.node.branch .leaf {
  width: 100%;
  height: 100px;
  background: blue;
}

.node.branch .body {
  width: 100%;
  display: flex;
  align-items: stretch;
}

.node.branch .body .tribe {
  width: 100px;
  background: blue;
  margin-right: 1px;
}

.node.branch .body .subnodes {
  padding-top: 1px;
  width: 100%;
  overflow: hidden;
}
<div class="node"></div>
<div class="node branch">
  <div class="leaf"></div>
  <div class="body">
    <div class="tribe">TRIBE</div>
    <div class="subnodes">
      <div class="node"></div>
      <div class="node"></div>
    </div>
  </div>
  <div class="leaf"></div>
</div>

The "tribe" element doesn't remain with a width of 100px.

Everything else works as supposed. Can I force it somehow? And by the way: is flex the true reason for this behavior?


回答1:


Flexbox items have flex-shrink parameter with default of 1. This means that in case your flexbox container don't have enough space its items will shrink.

To disable this behaviour for flexbox item set flex-shrink: 0.

Demo:

.node:not(.branch) {
  width: auto;
  height: 100px;
  background: red;
  margin-bottom: 1px;
}

.node.branch,
.node.branch .body {
  width: auto;
  overflow: hidden;
}

.node.branch .leaf {
  width: 100%;
  height: 100px;
  background: blue;
}

.node.branch .body {
  width: 100%;
  display: flex;
  align-items: stretch;
}

.node.branch .body .tribe {
  width: 100px;
  flex-shrink: 0; /* new */
  background: blue;
  margin-right: 1px;
}

.node.branch .body .subnodes {
  padding-top: 1px;
  width: 100%;
  overflow: hidden;
}
<div class="node"></div>

<div class="node branch">
  <div class="leaf"></div>

  <div class="body">
    <div class="tribe">TRIBE</div>

    <div class="subnodes">
      <div class="node"></div>
      <div class="node"></div>
    </div>
  </div>
  
  <div class="leaf"></div>
</div>


来源:https://stackoverflow.com/questions/44986439/fixed-width-child-is-shrinking-in-flexbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!