0

Say I have a portion of my HTML file that looks like this:

<div data-w="20px">
    <p>this is some text this is some text this is some text</p>
</div>

And the <div>'s width should equal data-w, as shown below.

div { width:[data-w]; }

I know I can use [attribute] as a selector, but honestly, this is not an alternative:

div[data-w=1px]{ width:1px; }
div[data-w=2px]{ width:1px; }
div[data-w=3px]{ width:1px; }
div[data-w=4px]{ width:1px; }
div[data-w=5px]{ width:1px; }
div[data-w=1px]{ width:1px; }
div[data-w=1px]{ width:1px; }
        (...)

Ideas?

Edit

I found a possible duplicate

Community
  • 1
  • 1
Dann
  • 87
  • 1
  • 8
  • 1
    Do you want `
    ` to be `20px`? If yes than there's no way you can do it without the attribute selector
    – Mr. Alien Dec 26 '12 at 18:48
  • @Mr.Alien yes, but I might make another `
    ` with `data-w`=another value.
    – Dann Dec 26 '12 at 18:50
  • Ya so why you don't want to go for attribute selector? any specific reason? – Mr. Alien Dec 26 '12 at 18:50
  • 1
    There's [`width: attr(data-w px)`](https://developer.mozilla.org/en-US/docs/CSS/attr), but it's still experimental. *However* , it seems to me that this would break the separation between content and presentation. – DCoder Dec 26 '12 at 18:51
  • Because it's a numeric value, that can go from 0 to some value, and I need a simpler way of doing so without a bunch of selectors. – Dann Dec 26 '12 at 18:52
  • If you don't want to make for each value a selector in css then the only way is to loop through all elements with the data-* attribute and do something depending on the value. That would be for sure in javascript. CSS is not made for such stuff. – Sven Bieder Dec 26 '12 at 18:56
  • 1
    If you can generate HTML with `data-w="20px"` why don't you generate HTML with `style="width:20px;"`? – Tom Dec 26 '12 at 19:03
  • @Tom I feared someone would ask that. That is because I don't want the HTML to override my CSS, rather than having the CSS change the HTML, according to the HTML. – Dann Dec 26 '12 at 19:04
  • The sample code describing the goal does not match the verbal description. – Jukka K. Korpela Dec 26 '12 at 19:46

2 Answers2

1

The easiest way would be to use jQuery I suppose.

Fiddle.

$("div").each(function() {
    var w = $(this).data("w");
    var $this = $(this);

    $this.width(w);
});​

As said in the comments, this is impossible to do in mere CSS.

Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
0

I guess, because you are hardcoding the width, it would be better to use:

<div style="width:20px">
    <p>this is some text this is some text this is some text</p>
</div>
David Strencsev
  • 1,065
  • 11
  • 11