duskwuff duskwuff - 3 months ago 29
CSS Question

Prevent line break after inline-block

In a page, I have a container of fixed width which contains an inline-block element, followed by some text.

Sometimes, this text will be wider than the container. When this happens, I want it to break to the next line (as seen in the first example below).

Sometimes, this text will also be too wide to display within the container. When this happens, I want the excess to be truncated (

overflow: hidden
). However, when I try doing this the obvious way, a line break gets inserted after the inline-block element (as seen in the second example).

I can work around this by wrapping the inline-block element and the first letter of the text together in a
element (as seen in the third example -- or an equivalent
wrapper), but this seems like a really ugly way of going about things. Is there a better way of doing this?

.container {
outline: 2px solid blue;
width: 150px;
overflow: hidden;
margin: 10px;

.inlineblock {
display: inline-block;
width: 30px; height: 1.5em; vertical-align: middle;
background: gray;

<div class="container">
<span class="inlineblock"></span>line breaks only at spaces

<div class="container">
<span class="inlineblock"></span>widetextwidetextwidetext second line

<div class="container">
<nobr><span class="inlineblock"></span>w</nobr>idetextwidetextwidetext ugly workaround


It looks like the first character doesn't need to be in the <nobr> element, so this will work:

<nobr><span class="inlineblock"></span></nobr>wide...

Still ugly, but definitely less ugly! It works on Firefox and Chrome at least.