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.0

 

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.

Obviously, this is tongue-in-cheek but it’s still kinda cool 😉

Latest blog posts

Change is here! Pixel Pixel launches its new website.

You've probably noticed by now, but our site has had a bit of a rebuild - here's ...

Christmas Business Update

As we prepare to say goodbye to 2021 and welcome in the new year we wanted to share some equally ...

Our Work

We evolved an existing forms system to become an integral part of GWR’s business operations.

We created a website for Europe’s leading product management training provider.

Contact us