Dynamically generated HTML link icons .. with CSS-only!

Mate Marschalko
6 min readMar 31, 2022

Yes we could add icons to links by simply assigning classes or IDs. But could we dynamically add icons by analysing file names, links or the existence of certain attributes?

Yes we can! All with the CSS attribute selector.

CSS attribute selectors

The simplest version of the attribute selector can check if an attribute exists on any of the elements:

[href] {
text-decoration: underline;
font-weight: bold;
}

This selector will select every element on the page with a href attribute. We have more complex versions of this selector that can check if the value of the attribute begins with, ends with or contains a specific piece of text. Let’s see how we can use these in conjunction with pseudo-elements.

What we are going to do is automatically add icons to different links depending on their behaviour and the type of URLs they have.

Feel free to browser the source files of this project (along with all my previous and upcoming projects):

--

--

Mate Marschalko

Senior Creative Developer, Generative AI, Electronics with over 15 years experience | JavaScript, HTML, CSS