Using HTML Attributes in Generated Content

Generated content using CSS (i.e.: inserting a colon after each label element) can be a great way to ensure that content appears no matter what has been put in the container. However, when dealing with certain types of content and internationalization, this approach is quickly scrapped for a server-side insertion of the content. There may also be cases when you want to access and modify the generated content with Javascript, but cannot figure out an easy way to and, again, scrap the generated content in CSS in favor of generation in Javascript. There is a little known and used way, however, of controlling your generated content from HTML and Javascript.

The W3C spec on generated content, like all other W3C recommendation documents, is a wealth of information provided you don’t fall asleep reading it. I tend to check it every so often when working in CSS to see if there is some easier or more interesting way of doing something I’ve been doing all along. It’s never the easiest reference to learn from, and often has terrible examples, but it will at least get you searching for a better explanation of a particular property or value.

The spec on generated content describes a function you can call within CSS called attr() that, when passed an attribute name, will check the currently scoped element for said attribute and, if it exists, will grab its value and place it in the value of the content property. Using this method, we can set a data attribute to our generated content within HTML or Javascript. You can check out a quick example.

There is also a W3C draft for CSS3 values and units that describes using the attr function for a number of other properties, although currently they’re not supported in any major browser. However, it is exciting to think that one day we’ll be changing background colors of before and after pseudo-elements by simply changing an attribute on its parent.