GFL
GFL

Reputation: 1446

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?

Upvotes: 3

Views: 1580

Answers (2)

Oriol
Oriol

Reputation: 288710

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>

Upvotes: 2

Adam Buchanan Smith
Adam Buchanan Smith

Reputation: 9457

I think this is what you are going for https://jsfiddle.net/kvb5hb6f/14/

I removed the floats and changed it to an absolute position to the right, then added padding-right to the parent div so that the text on the left will not over lap the price on the right, then added the text-overflow: ellipsis; to the parent div.

div {
  background: #abcdef;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding-right: 50px;
}

.price {
  position: absolute;
  right: 0;
}

Upvotes: 3

Related Questions