固定宽度的子项在Flexbox中正在缩小 [英] Fixed width child is shrinking in flexbox

查看:38
本文介绍了固定宽度的子项在Flexbox中正在缩小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用 display:flex .

您可以在此处找到一个代码笔: https://codepen.io/chrispillen/pen/GEYpRg

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>

部落"元素的宽度不能保持100px.

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

其他所有功能均按预期进行.我能以某种方式强迫它吗?顺便说一句:flex是这种行为的真正原因吗?

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

推荐答案

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

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.

要为flexbox项集禁用此行为,请设置 flex-shrink:0 .

To disable this behaviour for flexbox item set 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>

这篇关于固定宽度的子项在Flexbox中正在缩小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆