Has anyone come up with a good solution to ensure that an icon is always next to the word preceding it (i.e., it never wraps to the next line)?
Run the code snippet below to see the problem…
div {
width: 52ch;
}
img {
width: 16px;
height: 16px;
}
<div>
The next sentence has a multi-word link where the (i) icon should always be next to the word "link".
This is a <a href="#">sample link<img src="https://www.svgrepo.com/show/20745/info.svg"></a>.
</div>
The goal is to always keep the (i) icon next to the word "link" so that it never becomes an orphan on the next line. If the sentence needs to wrap, then "link(i)" should wrap together as one unit.
Restrictions that I have no control over:
-
I cannot do this:
<a href="#">sample <span class="no-wrap">link<img src="https://www.svgrepo.com/show/20745/info.svg"></span></a>
-
I cannot use pseudo elements like
::before
and::after
to render the icon.
2
Answers
What you need is a
display: inline-block
property on youra
anchor tag. By default, thedisplay
property fora
isinline
.The main difference between both of them is
inline-block
will ensures everything inside the element stays within the same line (acts as 1 single element regardless of what is inside the element), whereasinline
will wrap to the next line if it runs out of space by creating new line inside the element, which is not what you want in this case.Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/display
An alternative approach is to make use of characters that force the browser to never make newline:
The
⁠
character isu2060
in unicode that stands for Zero width no-break space (Word-joiner), it renders nothing on screen but is actually a character that forces it to not break at this character in Flow Layout. When used together withwhite-space: nowrap
, the browser will not break at this character thus making sure the icon stays with the last word.use font awesome icons, with css pseudo element
::after
:Links