How to make ellipsis work in a flex container?
Asked Answered
Q

1

6

When I don't have display: flex on the .container the text properly truncates when decreasing the size of the container.

enter image description here

But the green block and the text aren't next to each other anymore, because the container doesn't have the display: flex. When I add it to the container, the green block and text are aligned properly but the text isn't truncated anymore (ellipsis are missing).

enter image description here

How can I make sure, using flex, that the block and text are aligned but also the text is truncated with the ellipses in a dynamic width container?

my example codepen

body {
  padding: 20px;
}

.container {
  display: flex;
}

.block {
  width: 25px;
  height: 25px;
  padding: 10px;
  background-color: yellowgreen;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px
}

.text {
  display: flex;
}

.truncate {
  flex: 1;
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 20pt;
}
<div class="container">
  <div class="block">B</div>
  <div class="text">
    <div class="truncate">
      3. This is a long string that is OK to truncate please and thank you
    </div>
  </div>
</div>
Quackery answered 3/6, 2019 at 16:33 Comment(0)
O
5

Your flex item with the ellipsis must be able shrink below the width of the content. See my answer here for complete details: Why don't flex items shrink past content size?

revised codepen

body {
  padding: 20px;
}

.container {
  display: flex;
  border: 1px dashed red; /* demo */
}

.block {
  flex: 0 0 25px;  /* flex-grow, flex-shrink, flex-basis */
                   /* set flex-shrink to 0 to prevent item from shrinking below 25px */
  padding: 10px;
  background-color: yellowgreen;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
}

.text {
  display: flex;
  min-width: 0; /* allow item to shrink below content size */
}

.truncate {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 20pt;
  background-color: yellow; /* demo */
}
<div class="container">
  <div class="block">B</div>
  <div class="text">
    <div class="truncate">
      3. This is a long string that is OK to truncate please and thank you
    </div>  
  </div>
</div>
Octameter answered 3/6, 2019 at 17:8 Comment(2)
Excellent! Thank you for your effort!Quackery
@TomAalbers all you need is min-width: 0; on text elementDialectical

© 2022 - 2024 — McMap. All rights reserved.