Tech News
← Back to articles

The attr() function in CSS now supports types

read original related products more articles

The attr() function in CSS is a powerful function that allows you to use the value of an attribute of an HTML element as the value of a CSS property. This function is commonly used with the content property in pseudo-elements to display the value of an attribute on the page.

The attr() function has been around for a while and is widely used in CSS. However, it was limited to only accepting a single argument: the name of the attribute whose value you wanted to use.

On top of that, the value returned by the attr() function was always treated as a string and so, you could only use it in properties that accept string values. For instance, the content property mentioned previously.

The new syntax with types

With the latest CSS specification, the attr() function has been updated to support types. This means that you can now specify the type of the value that the attribute should be treated as.

We can now use the attr() function with a lot of properties as a result. And that makes it a lot more powerful than it was before. This opens up a whole new world of possibilities for the attr() function.

The syntax for the new attr() function looks like so.

attr (< attribute-name > type (< specific-type >))

How to use attr() with types

For instance, if we want to specify the width of an element based on the value of the data-width attribute, we can do so like this.

... continue reading