【问题标题】:Flex item is squashed by it's own margin弹性项目被它自己的边距压扁
【发布时间】:2020-05-11 13:21:10
【问题描述】:

我有一个 flex 容器,里面有一个子元素,并且它附近有一个展开的文本。

孩子是一个具有明确宽度和高度的方形盒子,以及一个将其与文本分开的横向边距。

当文本太长而无法容纳容器的宽度并以多行换行时,框的宽度会缩小一点,而它的边距保持适当的值。

div {
  display: flex;
  border: 1px solid #D0D0D0;
  width: 200px;
}

span {
  width: 1em; /* both width and flex-basis yield same results */
  height: 1em;
  margin-right: 1em;
  background-color: black;
}
<div>
  <span></span> 
  box behaves normally
</div>

<div>
  <span></span> 
  box's width shrinks near a text which doesn't fit parent's width
</div>

谁能解释为什么盒子会缩小?

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    flex-shrink: 0 添加到span,因为问题是该项目默认具有flex-shrink: 1,这意味着它决定了弹性项目相对于弹性容器中的其余弹性项目将收缩多少行空间不足。

    div {
      display: flex;
      border: 1px solid #D0D0D0;
      width: 200px;
    }
    
    span {
      width: 1em;  /* both width and flex-basis yield same results */
      height: 1em;
      margin-right: 1em;
      background-color: black;
      flex-shrink: 0
    }
    <div>
      <span></span>
      box behaves normally
    </div>
    
    <div>
      <span></span>
      box's width shrinks near a text which doesn't fit parent's width
    </div>

    【讨论】: