3

I use attr(data-width) to get the data-width-attribute from some list-item's. I try to use these values to set the width of that element.

The problem is that css cannot handle strings as width/height-value. e.g.:

<foo data-width='100%'></foo>

/* can not work */
foo {
    width: attr(data-width)
}

so I need to convert the value from the data-attribute to an integer (+unit).

Is that somehow possible?

yckart
  • 32,460
  • 9
  • 122
  • 129
  • Definitely not a duplicate. Wrongly duped question happened on SO so frequently. For example, by converting to . Not only attr() may yield string values, but also counter() function. And attr() now accept a new parameter to convert its type. So this question is far from a duplicate of that one. – tsh Feb 23 '21 at 03:34

2 Answers2

8

No. And you cannot use an attr(...) construct as the value of a normal property, only in the value of a content property.

Instead of data-width attributes, you could use just style attributes. Not ideal, but more logical than to use data-* attributes to carry style info.

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390
-1

not without a precompiler and SASS / SCSS mixins

Brandt Solovij
  • 2,124
  • 13
  • 24
  • I don't think that this works: http://fiddle.jshell.net/pA3Kq/ – yckart Jun 05 '13 at 18:59
  • 1
    Preprocessors generate the CSS *first* and only the compiled CSS is sent to the browser. They have no way of taking the information from the DOM and turning it into an integer and CSS does not have that ability natively. – cimmanon Jun 05 '13 at 19:02
  • The fiddle doesn't make any sense because there's no content to make the element visible: http://fiddle.jshell.net/pA3Kq/1/. As you can see, the element does not extend all the way to the edge of the document. – cimmanon Jun 05 '13 at 19:10
  • @cimmanon just replace `attr(data-width)` with `100%` in my fiddle ;) – yckart Jun 05 '13 at 19:11
  • @PeeHaa埽 this was just a simple test using SCSS as preprocessor – yckart Jun 05 '13 at 19:13
  • @yckart Aaaaaaah. Now it's becoming clear :-) – PeeHaa Jun 05 '13 at 19:14