Super simple directives with CSS (sort-of)
Who needs a fancy front-end framework like Angular or React when we can simply use our old pal CSS?
How?!
The CSS attr() function lets you grab HTML attributes and use their values within your CSS.
This means that it is possible to *vaguely* approximate an mvc-style directive by changing the output of an element according to its attribute.
Sprinkle in a little javascript to update the attribute value when required and voila! One updated element without a controller in sight.
Sort of, anyway 🙂
Syntax:
content: attr();
- The syntax also allows for type definition and a fallback value – see MDN for the full details.
- Should degrade gracefully by simply not printing anything.
- It’s possible to use multiple attributes in tandem.
- You can add additional content or white space by appending/prepending some string-containing quotes to the attr() declaration.
e.g: content: ' some extra text ' attr(first) ' ' attr(second);
Examples:
HTML:
<span>Hello</span>
CSS:
span:after {
content: attr(name);
}
Output:
Hello John
See the Pen CSS attr() by Pixel Pixel (@pxpxltd) on CodePen.
Support:
Support is…poor 🙂
content
is the only CSS property that this will work with for now, so the concept is only really applicable to psuedo element content properties! Hopefully in the future support might be rolled out across browsers to allow the use of attr() for color, font-weight etc. where its use would be nifty.
- https://caniuse.com/#search=attr()
- https://developer.mozilla.org/en/docs/Web/CSS/attr
- https://www.w3schools.com/cssref/func_attr.asp
Obviously, this is tongue-in-cheek but it’s still kinda cool 😉