4

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?

1
  • 1
    Definitely not a duplicate. Wrongly duped question happened on SO so frequently. For example, by converting <string> to <integer>. 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. Commented Feb 23, 2021 at 3:34

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

~5 Years to accept your answer... Shame on me!
-1

not without a precompiler and SASS / SCSS mixins

6 Comments

I don't think that this works: fiddle.jshell.net/pA3Kq
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.
The fiddle doesn't make any sense because there's no content to make the element visible: fiddle.jshell.net/pA3Kq/1. As you can see, the element does not extend all the way to the edge of the document.
@cimmanon just replace attr(data-width) with 100% in my fiddle ;)
@PeeHaa埽 this was just a simple test using SCSS as preprocessor
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.