ic3
ic3

Reputation: 7680

Nested flex-shrink not working on nested div

Having some trouble to make a nested div shrink in a flex scenario.

It's a simplification of Material-UI chips, the idea is the chips to shrink their text when a line is full.

A simplified div structure looks like (we want the inner span to shrink) :

<div class="papa">
  <div class="child child1">Fixed-<span class="span">This is a long text that we want to shrink with ellipsis</span>-End</div>
  <div class="child child2">Fixed-<span class="span">This is a long text that we want to shrink with ellipsis</span>-End</div>
  <div class="child child3">Fixed-<span class="span">This is a long text that we want to shrink with ellipsis</span>-End</div>
</div>

How to make the inner span to shrink when there is no avaible space ?

Code example :

https://codepen.io/iccube/pen/abBgayz

Upvotes: 0

Views: 109

Answers (2)

Berci
Berci

Reputation: 3386

Just give the div with the class .child the ellipsis prop (like this):

LATER EDIT: I edited the code. I replaced the span with a div. (You can replace the div back to a span and add display: block to the .span class. But this is cleaner I think.) Basically you have to make sure that the text container will have the desired width, and since you cannot provide a fixed value for the width, the text you want to be truncated should have display: block

.papa {
  display: flex;
  flex-direction: row
  background-color: red
    oveflow: hidden;
}

.child {
  display: flex;
  white-space: nowrap;
  overflow: hidden;
}
.span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.child1 {
  background-color: lightblue;
}
.child2 {
  background-color: lightgreen;
}
.child3 {
  background-color: lightcoral;
}
<div class="papa">
  <div class="child child1">Fixed-<div class="span">This is a long text that we want to shrink with ellipsis</div>-End</div>
  <div class="child child2">Fixed-<div class="span">This is a long text that we want to shrink with ellipsis</div>-End</div>
  <div class="child child3">Fixed-<div class="span">This is a long text that we want to shrink with ellipsis</span>-End</div>
</div>

You can read more about overflow ellipsis here

Upvotes: 1

ssaakkaa
ssaakkaa

Reputation: 418

You need to specify width of the ".child" elements so flex know what to do with them. Solution is very simple here is the code you need to change:

.child {
  flex-shrink: 1;
  white-space: nowrap;
  display: flex;
  width: 33.33%;
}

one more thing if you need ".papa" element to have some max-width, you can just set the max-width like this:

.papa {
  display: flex;
  flex-direction: row;
  background-color: red;
  //SET YOUR MAX WIDTH
  max-width: 500px;
}

EDIT: If I understand you correctly you want this behaviour: https://codepen.io/ssaakkaa/pen/mdOZaJO

for that, you need to set overflow:hidden on the child elements

Upvotes: 1

Related Questions