Valores CSS usando el atributo de datos HTML5 [duplicar]


Esta pregunta ya tiene una respuesta aquí:

width: attr(data-width);

Quiero saber si hay alguna manera de que sea posible establecer un valor css usando el atributo data- de HTML5 de la misma manera que se puede establecer css content. Actualmente no funciona.


HTML

<div data-width="600px"></div>

CSS

div { width: attr(data-width) }
Author: Brian Tompsett - 汤莱恩, 2012-03-02

3 answers

Hay, de hecho, previsión para tal característica, mira http://www.w3.org/TR/css3-values/#attr-notation

Este violín debería funcionar como lo que necesita, pero no lo hará por ahora.

Desafortunadamente, todavía es un borrador, y no está completamente implementado en los principales navegadores.

Funciona para content en pseudo-elementos, sin embargo.

 73
Author: Caio Cunha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-12 09:43:30

Puede crear con javascript algunos css - rules, que luego puede usar en sus estilos: 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 + "%");
}

Esto crea 100 pseudo-selectores como este:

[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }

Nota: Esto es un poco fuera de tema, y no es realmente lo que usted (o alguien) quiere, pero tal vez útil.

 7
Author: yckart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-24 17:29:24

A partir de hoy, puede leer algunos valores de atributos HTML5 data en declaraciones CSS3. En Caiotoon's fiddle el código CSS puede usar las propiedades data para establecer el content.

Desafortunadamente no funciona para width y height (probado en Google Chrome 35, Mozilla Firefox 30 e Internet Explorer 11).

Pero hay un CSS3 attr() Polyfill de Fabrice Weinberg que proporciona soporte para data-width y data-height. Puedes encontrar el repositorio GitHub aquí: cssattr.js .

 6
Author: Benny Neugebauer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-14 11:04:23