Fun with pseudo‑elements
I’ve known for quite a while that, you could inject content into
HTML elements using CSS pseudo‑elements:
::after. But, they are way more useful than I originally thought…
The Simple Stuff
Simply put, pseudo‑elements let you inject CSS content immediately before or immediately after the content of the matched element.
For example, suppose I want all paragraphs in my document to start with the phrase “Yo dog, “. I could write:
Instead of using a string, one can also link to another resource using the
url() css function. Here is a style that matches any anchor with an absolute url and injects an icon after them.
Got It! Anything Else?
The other day I ended up on MDN page
content property. I noticed something new: the
attr() value returns the value of the attribute
on the element as a string. I can make a context hover for external
links to display thier
href by doing something like this:
And now you have a no-js hover for links…
One Step Further!
Things got more interesting when I realized I could
do the same with HTML5
data- attributes. Consider the following markup:
Then I could do something like this:
It almost shadow-dom-esque. It’s nice not having to know the internals
of how the element is going to consume the
data- attribute, one can
just update the elements’ state and be done.
The Future and Beyond…
There is one unimplemented feature that would also help make this
technique a lot more powerful: the optional
[type] argument of
attr() function. The spec defines such
behavior but, as of writing this no browsers implement it.
This would return the value of the
data-icon-url attribute, but intrept
it’s value as a url rather than just a string. It would be pretty useful
for injecting icons…