0

I am trying to truncate the long text in the span with id first-item, when the screen gets smaller. However, when margins are set on the parent, it cannot shrink and therefore truncate does not seem to work. I believe it is related to Why don't flex items shrink past content size? but I could not make it work.

body {
  display: flex;
  flex-direction: column;
}

main {
  display: flex;
  flex-direction: column;
  margin-left: auto;
  margin-right: auto;
}

#container {
  display: flex;
}

#first-item {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
<body>
  <main>
<div id="container">
  <span id="first-item">Long long long long long long long long long long long long long long long long long long long long long long long long long text to be truncated</span>
  <span>Shorter text</span>
</div>
  </main>
</body>

EDIT: As @AmauryHanser commented, there was a typo in the initial version of the post, which is now corrected. Even though it seems that the ellipsis is there, it can only shrink to a point and the problem is still there. Check the screenshot below.

enter image description here

Demetris
  • 2,981
  • 2
  • 25
  • 33
  • 2
    You have a typo `disaply: flex;` should be `display: flex;` – Amaury Hanser Aug 26 '22 at 12:22
  • Thank you @AmauryHanser . I have corrected it and it works. However, in my setup which there are no typos, it does not. I will try to reproduce again and edit the answer. – Demetris Aug 26 '22 at 12:36

1 Answers1

1

add max-width:100% to main

body {
  display: flex;
  flex-direction: column;
}

main {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  margin: auto;
}

#container {
  display: flex;
}

#first-item {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
<body>
  <main>
    <div id="container">
      <span id="first-item">Long long long long long long long long long long long long long long long long long long long long long long long long long text to be truncated</span>
      <span>Shorter text</span>
    </div>
  </main>
</body>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • It works, thanks. Could you please explain what is going on? How come making maximum width `100%` allows it to shrink further? – Demetris Aug 26 '22 at 19:45
  • 1
    @Demetris the issue is that the main element which is a flex item is overflowing the body due to the white-space:nowrap. Your issue starts there. If you limit the main to the body width then the container will follow it, same for first-item. Add borders to all the element before the fix to better identify the issue – Temani Afif Aug 26 '22 at 20:10