I have this HTML code:
<div data-width="70"></div>
I want to set it's width in CSS equal to the value of data-width attribute, e.g. something like this:
div { width: [data-width]; }
I saw this was done somewhere, but I can't remember it. Thanks.
The [attribute^="value"] selector is used to select elements with the specified attribute, whose value starts with the specified value. The following example selects all elements with a class attribute value that starts with "top": Note: The value does not have to be a whole word!
While attr() is supported for effectively all browsers for the content property, CSS Values and Units Level 5 adds the ability to use attr() on any CSS property, and to use it for non-string values (e.g. numbers, colors).
The CSS Attribute Selector is used to select an element with some specific attribute or attribute value. It is an excellent way to style the HTML elements by grouping them based on some specific attributes and the attribute selector will select those elements with similar attributes.
You need the attr
CSS function:
div { width: attr(data-width); }
The problem is that (as of 2021) it's not supported even by some of the major browsers (in my case Chrome):
You cant pass data attribute value directly in to css without pseudo type content. Rather you can do this way.. CHECK THIS FIDDLE
<div data-width="a"></div><br> <div data-width="b"></div><br> <div data-width="c"></div>
CSS
div[data-width="a"] { background-color: gray; height: 10px; width:70px; } div[data-width="b"] { background-color: gray; height: 10px; width:80px; } div[data-width="c"] { background-color: gray; height: 10px; width:90px; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With