Pixel Pixel use Cookies.

We use cookies to enable essential services and functionality and to collect data on how visitors interact with our site. By clicking Accept Cookies, you agree to our use of all relevant cookies.

Certain cookies are unfortunately fundamental to the operation of the site and are thus required - you can find out more by viewing our Cookie Policy.

You can manage your preferences at any time via our Cookie Preferences manager.


Manage Preferences

Manage Cookie Preferences for Pixel Pixel

You can find out more about by checking out our Cookie Policy

  • Essential

    Unfortunately certain cookies are essential to the operation of our site and are a condition of its use.

  • Performance

    Collects anonymous data about how visitors use our site and how it performs.

  • Support

    These cookies assist us in providing a great service every time. They may include CRM or feedback tools.

Get in touch
Featured image for Super simple directives with CSS (sort-of)

Super simple directives with CSS (sort-of)

Posted on 15th February 2018 at 11:30am by Chris Snowden in Code, Tutorials, Web

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

----

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 ;)


We love what we do! You will too. Speak to us