
Adding an image before a link with CSS.
Published: 01-Apr-2025, by maardal
Technologies mentioned in this blog post
css
html
Introduction
Sometimes I find myself wanting to add an image ahead of a link. Either to add another visual clue that a text is a link, or to display the logo of that specific website. One example can be adding the GitHub logo before any link that has an URL that directs to GitHub.
That is what I am going show you how to do in this post!
How To
How we are gonna solve this problem is by using the ::before pseudo element, and adding a background image to it.
a[href*='github']::before {
content: '';
display: inline-block;
height: 2rem;
width: 2rem;
background-image: url('https://upload.wikimedia.org/wikipedia/commons/9/91/Octicons-mark-github.svg');
background-size: 2rem 2rem;
background-repeat: no-repeat;
margin-left: 0.15rem;
}
Let’s walkthrough this quickly. The selector targets the pseudoelement before for anchor tags with an href-attribute value with a text that includes “github”. The matching on the text in the attribute is case insensitive.
For the declarations we start with setting the content to an empty string. This will take make it so that the before pseudoelement has no size, or dimensions. We therefore need to set it’s height and width.
To be able to set the element’s dimensions we need to consider the type of element we’re targeting. Different elements has different display values. A paragraph element is a block element, while our anchor tag here is an inline element. An display of inline does NOT let us set the size of the element. Therefore we need to change the display to inline-block. We then set the dimensions we want the element to have. I also add a little margin to the left of the element, to have some space between the image and the follwing text.
The last step is to add the GitHub logo as an background image. We set it’s size to match the element’s size so it takes up the full element size. To be safe, we set the background to not repeat.
And that’s it! 🥳
Further reading
Below I show the CodePen I made for this little post, and I talk about an advantage of using this method, over adding an image in HTML front of the link.
Check it out if you’re curious 😃.
Codepen
Advantage
An advantage with this method is avoiding problems with accessibility for screen readers. Let me take you through a scenario.
Another way to solve this problem is to add an img tag before the link. The img tags needs an alt tag describing the image.
Let’s say the alt text is “logo of GitHub.com”.
A screen reader will read this alt tag, and then it will encounter the link. It will then read “link” and the text we put between the anchor tags.
Essentially, it will read unncessary information for the screen reader user.
Adding the image through CSS, we avoid having to add the alt text, and it will be ignored by a screen reader.