Anidamiento de clases CSS


Puedo hacer algo como lo siguiente?

.class1{some stuff}

.class2{class1;some more stuff}
Author: TylerH, 2010-12-30

8 answers

No es posible con CSS vainilla. Sin embargo, puedes usar algo como:

Sass hace que CSS sea divertido de nuevo. Sass es un extensión de CSS3, añadiendo anidados reglas, variables, mixins, selector herencia, y más. Está traducido a CSS estándar bien formateado usando la herramienta de línea de comandos o plugin de web-framework.

O

En lugar de construir un selector largo nombre para especificar la herencia, en menos simplemente puede anidar selectores dentro otros selectores. Esto hace herencia clara y hojas de estilo más corto.

Ejemplo:

#header {
  color: red;
  a {
    font-weight: bold;
    text-decoration: none;
  }
}
 46
Author: Sarfraz,
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
2010-12-30 17:49:37

No con CSS puro. El equivalente más cercano es este:

.class1, .class2 {
    some stuff
}

.class2 {
    some more stuff
}
 33
Author: cdhowie,
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
2010-12-30 17:49:48

Actualización: Existe una especificación CSS3 para el anidamiento de CSS de nivel 3. Actualmente es un borrador. https://tabatkins.github.io/specs/css-nesting /

Si se aprueba, la sintaxis se vería así:

table.colortable {
  & td {
    text-align:center;
    &.c { text-transform:uppercase }
    &:first-child, &:first-child + td { border:1px solid black }
  }
  & th {
    text-align:center;
    background:black;
    color:white;
  }
}

Situación: El Grupo de Trabajo no aprobó la propuesta spec.

 28
Author: etoxin,
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
2018-05-01 06:48:41

No directamente. Pero puede usar extensiones como LESS para ayudarlo a lograr lo mismo.

 4
Author: RabidFire,
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
2010-12-30 17:49:38

No.

Puede usar selectores de agrupación y/o múltiples clases en un solo elemento, o puede usar un lenguaje de plantilla y procesarlo con software para escribir su CSS.

Véase también mi artículo sobre Herencia CSS.

 3
Author: Quentin,
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
2010-12-30 17:49:48

Prueba esto...

Dale al elemento un ID, y también un nombre de clase. Luego puedes anidar el # IDName.className en tu CSS.

Aquí hay una mejor explicación https://css-tricks.com/multiple-class-id-selectors /

 1
Author: Oz The Tech Guy,
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
2016-08-23 08:06:10

No creo que esto sea posible. Se puede añadir class1 a todos los elementos que también tienen class2. Si esto no es práctico de hacer manualmente, podría hacerlo automáticamente con JavaScript (bastante fácil de hacer con jQuery).

 0
Author: Kyle,
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
2010-12-30 17:51:43

Puedes hacerlo usando Javascript:

static generateStyle = (parentSelector, allCss) => {
  const reg = /(.+?)\s?\{\s?(.+?)\s?\}+/g;
  const matches = allCss.match(reg);
  const styles = [];

  for (let i = 0; i < matches.length; i++) {
    const cssDecleration = matches[ i ];

    if (cssDecleration.indexOf('@media') === -1) {
      styles.push(`${ parentSelector } ${ cssDecleration }`);
    }
    else {
      const mediaPos = cssDecleration.indexOf('{');

      if (mediaPos === -1) {
        continue;
      }

      const mediaQuery = cssDecleration.substring(0, mediaPos);
      const rest = cssDecleration.substring(mediaPos);
      const restPlaced = MicroServiceData.generateStyle(parentSelector, rest);

      styles.push(`${ mediaQuery } ${ restPlaced }`);

    }
  }

  return styles.join('\n');
};
 0
Author: yairniz,
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
2018-06-28 08:08:06