Craft Web Design + Development
Brendan McKeown

Hey there. I’m a front-end developer and web designer. I'm all about creating websites and web apps that look and perform flawlessly on any device using HTML, CSS, and Javascript. I enjoy utilizing libraries, frameworks and preprocessors that improve efficiency and reduce confusion.

Check out my resume.

Prevent :after Psuedo Element from Wrapping

I like using the ::after pseudo class for inserting icons inline after some text. No extra markup is required, and you can easily use a sprite to supply the graphic.

<a href="#" class="icon-link">The icon should not wrap by itself.</a>
.icon-link {
    display: inline-block;
}
.icon-link:after {
    content:"";
    display: inline-block;
    width: 32px;
    height: 32px;
    margin-bottom: -10px;
    /* background: ... */
}

However, the icon will wrap (undesirably) like it is a word. This is what I'm talking about:

pseudo element icon

It would look much better if the icon was stuck to the last word and wrapped with it. Like this:

pseudo element icon

The solution for this is a little unintuitive, but is pretty simple and works well. By adding a positive padding-right to the parent selector, and a negative margin-right to the pseudo class (both values being the width of the icon), the icon will stick to the last word and not wrap by itself.

<a href="#" class="icon-link">The icon should wrap with the last word.</a>
.icon-link {
    display: inline-block;
    padding-right: 32px;
}
.icon-link:after {
    content:"";
    display: inline-block;
    width: 32px;
    height: 32px;
    margin-right: -32px;
    margin-bottom: -10px;
    /* background: ... */

The only caveat here is that you are unable to add any spacing between the text and icon using margins or padding. Instead, you would have to add this spacing to the image itself.

Try it on jsFiddle