Search code examples
htmlcssflexboxellipsis

Text-overflow:ellipsis and Flexbox


I want to have a box with text and an Icon inside. The Icon is supposed to stick to the right side of the box, the text to the left. If the text is too long to fit into the box next to the icon, I want it to be shortend by the text-overflow:ellipsis property. I do not insist on implementing it with Flex-Box, if there is a better way to do it.

It should look like this:

enter image description here

And this is what I achieved so far:

div#Wrapper {
  border: 0.2em solid black;
  width: 6em;
  padding: 0.5em;
  display: flex;
}


span#Text {
  white-space: nowrap;
  text-overflow: ellipsis;
}


span#Icon {
  background-color: blue;
  border-radius: 50%;
  height: 1em;
  width: 1em;
  display: inline-block;
  margin-left: auto;
}
Short Text:
<div id="Wrapper">
  <span id="Text">
    This
  </span>
  <span id="Icon"> 
  </span>
</div>

<br><br><br>

Text:
<div id="Wrapper">
  <span id="Text">
    This is Text
  </span>
  <span id="Icon"> 
  </span>
</div>

<br><br><br>

Long Text:
<div id="Wrapper">
  <span id="Text">
    This is long long long Text
  </span>
  <span id="Icon"> 
 
  </span>
</div>


Solution

  • You can add flex: 1 and overflow: hidden properties on text element.

    div#Wrapper {
      border: 0.2em solid black;
      width: 6em;
      padding: 0.5em;
      display: flex;
    }
    span#Text {
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    span#Icon {
      background-color: blue;
      border-radius: 50%;
      height: 1em;
      width: 1em;
      margin-left: auto;
    }
    <div id="Wrapper">
      <span id="Text">
        This is long long long Text
      </span>
      <span id="Icon"></span>
    </div>