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. First, specify the data attribute on the element you want to customize. <div data-width="100px"></div> Then, in the CSS, we can use the attr() function with the type() function to specify that the value of the data-width attribute should be treated as a <length> type. div { width: attr(data-width type(<length>)); } As you can tell, the <length> type represents a distance value and it works perfectly with the width property. This will set the width of the div element to 100px. A practical example Let’s say, we want to build a Chart-like UI where we want to customize the width of the div elements based on the value of the data-w...
First seen: 2025-08-22 02:42
Last seen: 2025-08-22 03:48