GFL GFL - 3 months ago 12
CSS Question

Prevent float from wrapping and force text-overflow when needed

I have three fields I would like on one line:

<div><span class="name">Blue Widgets Over Miami</span><span class="size"> large </span><span class="price">$9.99</span></div>


I'd like .name and .size to be on the left side of the line, .price on the right, and to always have at least a space between each field.

Here's the tricky part though. If the screen is really narrow, I don't want the div to wrap or overflow. Instead I'd like for .name to text-overflow as an ellipsis.

div{background:#abcdef;white-space:nowrap}
.name{text-overflow:ellipsis}
.size{}
.price{float:right}


Right now if the screen is narrow then .price drops to a second line (which I don't want), and if the screen is even narrower then .name and .size overflow the div (which I also don't want), and .name never truncates with some ellipsis.

What am I doing wrong?

Answer

Use flexbox:

div {
  background: #abcdef;
  display: flex;
}
.name {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.size {
  margin: 0 .5em;
}
.price {
  margin-left: auto;
}
<div>
  <span class="name">Blue Widgets Over Miami</span>
  <span class="size">large</span>
  <span class="price">$9.99</span>
</div>
<br />
<div>
  <span class="name">Blue Widgets Over Miami Blue Widgets Over Miami Blue Widgets Over Miami Blue Widgets Over Miami Blue Widgets Over Miami Blue Widgets Over Miami Blue Widgets Over Miami Blue Widgets Over Miami Blue Widgets Over Miami Blue Widgets Over Miami</span>
  <span class="size">large</span>
  <span class="price">$9.99</span>
</div>