【问题标题】:When we give a fixed width to an element why it is taking less that that fixed width when its nearby content is changing in case of display flex [duplicate]当我们为元素提供固定宽度时,为什么在显示 flex 的情况下其附近内容发生变化时它占用的固定宽度小于固定宽度 [重复]
【发布时间】:2019-09-01 15:03:40
【问题描述】:

我有一个标签和一个按钮,我给按钮一个固定的宽度,如果标签文本更小,它会占用给定的宽度,但是当标签文本增加时,按钮占用的宽度会更小。

为什么会这样?

我没有给标签指定任何宽度。

HTML

<div>
  <label>Some text now this text is incrasinf </label>
  <button>Button</button>
</div>

CSS

div {
  border: solid green;
  width: 200px;
  display: flex;
}

label {
    border: solid blue;
    display: flex;
    flex-grow:1;
}

button {
  width: 100px;
}

当标签文本很小时,按钮按预期占用 100px。

当标签文本增加按钮占用小于 100px 时(出乎我的意料)

Codepen 链接https://codepen.io/anon/pen/OGmMpd

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    在按钮上添加flex-shrink: 0 - 默认flex-shrink: 1,所以根据内容的变化flex items可以shrink .

    请看下面的演示:

    div {
      border: solid green;
      width: 200px;
      display: flex;
    }
    
    label {
      border: solid blue;
      display: flex;
      flex-grow: 1;
    }
    
    button {
      width: 100px;
      flex-shrink: 0; /* added */
    }
    <div>
      <label>Some text now this text is incrasinf </label>
      <button>Button</button>
    </div>

    【讨论】:

      猜你喜欢
      • 2015-05-17
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      • 2015-06-22
      相关资源
      最近更新 更多