Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of attribute in CSS

Tags:

html

css

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.

like image 608
Amar Syla Avatar asked Aug 18 '13 15:08

Amar Syla


People also ask

How do I target a value in CSS?

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!

Can I use attr ()?

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

How do you target a style attribute in CSS?

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.


2 Answers

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

enter image description here

like image 90
Amar Syla Avatar answered Sep 17 '22 13:09

Amar Syla


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; } 
like image 33
Vikas Ghodke Avatar answered Sep 19 '22 13:09

Vikas Ghodke