There is a content property in CSS that’s made to use in tandem with the ::before and ::after pseudo elements. It injects content into the element.
Here’s an example:
content: attr(data-done) Email: ; /* This gets inserted before the email address */
The property generally takes anything you drop in there. However, there are some invalid values it won’t accept. I heard from someone recently who was confused by this, so I had a little play with it myself and learned a few things.
This works fine:
/* Valid */
…but this does not:
/* Invalid, not a string */
I’m not entirely sure why, but I imagine it’s because 1 is a unit-less number (i.e. 1 vs. 1px) and not a string. You can’t trick it either! I tried to be clever like this:
/* Invalid, no tricks */
You can output numbers from attributes though, as you might suspect:
/* This works */
content: $ attr(data-price);
But of course, you’d never use generated content for important information like a price, right?! (Please don’t. It’s not very accessible, nor is the text selectable.)
Even though you can get and display that number, it’s just a string. You can’t really do anything with it.
/* Not gonna happen */
calc(attr(data-price) * attr(data-sale-modifier));
You can’t use numbers, period:
/* Nope */
content: calc(2 + 2);
/* These will break */
content: 1 . 2 . 3;
content: 1 + 2 + 3;
/* Use spaces */
content: 1 2 3;
/* Or nothing */
content: 1 2 3;
/* The type of quote (single or double) doesnt matter, but content not coming back from attr() does need to be quoted. */
There is a thing in the spec for converting attributes into the actual type rather than treating them all like strings…
width: attr(length em); /* or other values like number, px, or url */
…but I’m fairly sure that isn’t working anywhere yet. Plus, it doesn’t help us with pseudo elements anyway, since strings already work and numbers don’t.
The person who reached out to me over email was specifically confused why they were unable to use calc() on content. I’m not sure I can help you do math in this situation, but it’s worth knowing that pseudo elements can be counters, and those counters can do their own limited form of math. For example, here’s a counter that starts at 12 and increments by -2 for each element at that level in the DOM.
See the Pen Backwards Double Countdown by Chris Coyier (@chriscoyier) on CodePen.
The only other thing we haven’t mentioned here is that a pseudo element can be an image. For example:
…but it’s weirdly limited. You can’t even resize the image. ¯\_(?)_/¯
Much more common is using an empty string for the value (content: 😉 which can do things like clear floats but also be positioned, sized and have a background of its own.