Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text overflow in css flexBox can be solved by simply add width:0, but why? [duplicate]

Tags:

css

flexbox

.textEllipsis{
  overflow: hidden;
  text-overflow: ellipsis;
  white-space:nowrap;
}

.wrapper{
  display: flex;
  width: 500px;
  padding: 10px;
  background: green;
}

.wrapper .main,.sub{
  padding: 10px;
}

.wrapper .main{
    flex: 1;
    background: red;
}

.wrapper .main.widthConfig{
  width: 0;
}

.wrapper .sub{
  width: 100px;
  flex-shrink: 0;
  background: blue;
  color: #fff;
}
<h3>right behavior</h3>
<div class="wrapper">
  <div class="main widthConfig">
    <div class="inner textEllipsis">
adfadfafasfafasdfasdfasdfasfafasdfasdfasdfasfafasdfasdfasdfasfafasdfasdfasdfasfafasdfasdfasdfasf
    </div>
  </div>
  <div class="sub">
    aaaaaaaaaaa
  </div>
</div>
<h3>remove width: 0 get wrong behavior</h3>

<div class="wrapper">
  <div class="main">
    <div class="inner textEllipsis">
adfadfafasfafasdfasdfasdfasfafasdfasdfasdfasfafasdfasdfasdfasfafasdfasdfasdfasfafasdfasdfasdfasf
    </div>
  </div>
  <div class="sub">
    aaaaaaaaaaa
  </div>
</div>

In the snippet, I create an flexBox layout with .wrapper element. And I add flex:1 to the .main element, add a fixed width like width: 100px to the sub element. In the child element of .main element I add some long text then the width of .main element is out of control.

But when I add width: 0 to the .main element everything turn right. Can any body tell me why?

like image 695
wxttt Avatar asked Jan 23 '26 19:01

wxttt


1 Answers

Set min-width: 0; on the flex child

Or set min-width to some actual value.
Without this, the flex child containing the other text elements won’t narrow past the "implied width" of those text elements.

According to a draft spec, the above text should not fully collapse when the flex container is resized down. Because subtitle has a width of 100%, the min-width: auto calculation that flex-box makes says that its container should be larger than we want.

This behavior is consistent across Chrome, Opera, and Firefox. Safari was shrinking/truncating even without the min-width (which is against the specs, I think).

like image 73
Yash Chitroda Avatar answered Jan 25 '26 09:01

Yash Chitroda