Scott Simpson
Scott Simpson

Reputation: 3850

Keep last word and image on same line

With CSS, is there a way to break both the last word and the image to a new line at the narrower width?

http://jsfiddle.net/2koc2deo/3/

.text-two {
   width: 125px;
}
.text {
   font-size: 16px;
}
<div class="text text-one">
   <p><a href="#">Customer Service&nbsp;<img src="http://lorempixel.com/15/15/" alt=""></a>
</div>

<div class="text text-two">
   <p><a href="#">Customer Service&nbsp;<img src="http://lorempixel.com/15/15/" alt=""></a>
</div>

Upvotes: 4

Views: 2141

Answers (2)

showdev
showdev

Reputation: 29168

I added a negative right margin to the <a> elements, to match the image width.
This prevents the images from triggering a line wrap.
The line will only wrap if the text itself doesn't fit.

This works best in contexts where the right overflow of the container will still be visible.

.text {
  font-size: 16px;
}

.text-two {
  width: 118px;
}

.text a {
  margin-right: -15px;
}
<div class="text text-one">
  <p><a href="#">Customer Service&nbsp;<img src="https://fakeimg.pl/15x15/" alt=""></a></p>
</div>

<div class="text text-two">
  <p><a href="#">Customer Service&nbsp;<img src="https://fakeimg.pl/15x15/" alt=""></a></p>
</div>

This solution is inspired by Beauceron's answer to "Attach font icon to last word in text string and prevent from wrapping"

Upvotes: 3

Ryan Shillington
Ryan Shillington

Reputation: 25088

I couldn't get the above to work. I fixed mine by putting a span around the last word and the image and use white-space: nowrap;.

Here's a fiddle:

.text-two {
   width: 125px;
}

.text {
   font-size: 16px;
}

.no-wrap {
   white-space: nowrap;
}
<div class="text text-two">
   <p>Customer <span class="no-wrap">Service <img src="http://lorempixel.com/15/15/" alt=""></span></p>
</div>

Upvotes: 0

Related Questions