width: attr(data-width);
I want to know if there's any way it's possible to set a css value using HTML5's data-
attribute the same way that you can set css content
. Currently it doesn't work.
HTML
<div data-width="600px"></div>
CSS
div { width: attr(data-width) }
This question is related to
css
html
attributes
As of today, you can read some values from HTML5 data
attributes in CSS3 declarations. In CaioToOn's fiddle the CSS code can use the data
properties for setting the content
.
Unfortunately it is not working for the width
and height
(tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).
But there is a CSS3 attr() Polyfill from Fabrice Weinberg which provides support for data-width
and data-height
. You can find the GitHub repo to it here: cssattr.js.
You can create with javascript some css-rules
, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/
var addRule = (function (sheet) {
if(!sheet) return;
return function (selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
}
}(document.styleSheets[document.styleSheets.length - 1]));
var i = 101;
while (i--) {
addRule("[data-width='" + i + "%']", "width:" + i + "%");
}
This creates 100 pseudo-selectors like this:
[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }
Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.
Source: Stackoverflow.com