Combine calc() with attr() in CSS

Loupax picture Loupax · Dec 10, 2013 · Viewed 38.1k times · Source

I was wondering whether I can combine the calc() function with the attr() function to achieve something like the following:

<div class="content" data-x="1">
    This box should have a width of 100px
</div>

<div class="content" data-x="2">
    This box should have a width of 200px
</div>

<div class="content" data-x="3">
    This box should have a width of 300px
</div>

CSS

.content{
    //Fallback. If no calc is supported, just leave it at 100px
    width: 100px;
}


.content[data-x]{
    // Multiply the width of the element by the factor of data-x
    width: calc(100px * attr(data-x));
}

The draft says it should work, but in my case (Chrome 31.0.1650.63 m and Firefox 25.0.1 ) it doesn't. There are two cases then:

  1. I did it wrong
  2. It is not supported yet

Whats the deal?

Example Fiddle

Answer

jede picture jede · Dec 10, 2013

Right now attr() is not supported by default in any major browser for any attributes other then "content". Read more about it here: https://developer.mozilla.org/en-US/docs/Web/CSS/attr