【问题标题】:Fixed width child is shrinking in flexbox [duplicate]固定宽度的孩子在 flexbox 中缩小 [重复]
【发布时间】:2017-12-12 16:14:07
【问题描述】:

我是第一次使用display:flex

您可以在此处找到代码笔: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>

“tribe”元素不会保持 100 像素的宽度。

其他一切都按预期工作。我可以以某种方式强迫它吗?顺便问一下:这种行为的真正原因是 flex 吗?

【问题讨论】:

标签: html css flexbox


【解决方案1】:

Flexbox 项目具有flex-shrink 参数,默认为1。这意味着如果您的 flexbox 容器没有足够的空间,它的项目将会缩小。

为 flexbox 项目集 flex-shrink: 0 禁用此行为。

演示:

.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>

【讨论】:

    猜你喜欢
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2019-07-31
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多