弹性商品以自己的余量压扁

我有一个带单个孩子的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>

enter image description here

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

评论
  • Glora
    Glora 回复

    Wrap the textNode with some tag (in this case I added a div) so it can be a sibling of the span and add flex-shrink: 0 to span, as the problem is that item has by default flex-shrink: 1, which means it determines how much the flex item will shrink relative to the rest of the flex items in the flex container when there isn’t enough space on the row.

    Other fix would simple set flex:1 in div

    section {
      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
    }
    <section>
      <span></span>
      <div>box behaves normally</div>
    </section>
    
    <section>
      <span></span>
      <div>box's width shrinks near a text which doesn't fit parent's width</div>
    </section>