Search code examples
htmlcsscss-floatellipsis

Single-line text not truncating as expected in float layout


I have a basic HTML structure with a parent div and two children: span and a. The a is floated right, and I want the span to grow with the size of its text content until it hits the floated a, at which point I want the text to truncate with ellipses.

Here's a link to a JSFiddle: https://jsfiddle.net/56ua0jc8/

.parent {
  border: solid 1px black;
  overflow: hidden;
}

.text {
  border: solid 1px green;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.link {
  border: solid 1px red;
  float: right;
}
<div class="parent">
  <span class="text">Some text that is so long that it's pushing the link down instead of truncating. What I really want is for the text to truncate with ellipses instead.</span>
  <a class="link" href="someUrl">Link</a>
</div>

Currently the span is expanding and pushing down the floated a without truncating the text. How can I get this working?


Solution

  • I suggest to drop float and enter flexbox world:

    .parent {
      border: solid 1px black;
      display: flex; /*declare flexfox*/
    }
    
    .text {
      border: solid 1px green;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .link {
      border: solid 1px red;
      margin-left: auto; /*push it to the right*/
    }
    <div class="parent">
      <span class="text">Some text that is so long that it's pushing the link down instead of truncating. What I really want is for the text to truncate with ellipses instead.</span>
      <a class="link" href="someUrl">Link</a>
    </div>