CSS method for adding "new window" icon to external links

Use this CSS to add the "opens in a new window" icon to all external links:


a[href^="http://"]:after, a[href^="https://"]:after, a[href^="//"]:after {
    background: url('/images/open-in-new-window.png') center/contain;
    width: 0.8em;
    height: 0.8em;
    display: inline-block;
    content: " ";
    margin-left: 2px;
    color: transparent;
}

Note that you will need to revert to Javascript (or jQuery) if you want to add the actual "target=_blank" attribute to these links. I typically add this manually, but you may prefer to have a bit of code in place to make sure that it's always there. Another approach is to simply assign the new-window icon to all links that contain the new-window attribute:


a[target="_blank"]:after {
    background: url('/images/open-in-new-window.png') center/contain;
    width: 0.8em;
    height: 0.8em;
    display: inline-block;
    content: " ";
    margin-left: 2px;
    color: transparent;
}

Exemptions

To exclude certain links from this styling, simply over-ride it. For example, I don't want my "social share" links to have the new-window icon after them, so I do this:


a.share:after {
    background: none !important;
    display: none !important;
}

See it in action!


Comments

by km on 10 November 2018
THANK YOU!!!!!! You just saved me HOURS of trying to figure this out on my own.
Reply
Add your comment