Especificidad CSS

Assuming this mark-up:

<html class="fr">
<head>
</head>
<body>
 <div class="class1">
 </div>
</body>
</html>

¿Esto?

.fr .class1 {
  background-color: blue;
}

take precedence over this:

.class1 {
  background-color: red;
};

Edit:

To those wondering, yes I had tried :) I didn't explain the full problem here and discovered the issue after this post.

Basically, I had two styles in the same stylesheet:

.fr .class1 {
  font-size: 12px;
}

.class1 {
  font-size: 12px;
  line-height: 18px;
  height: 80px;
}

Aunque técnicamente .fr .class1 toma precendence encima .class1, this doesn't mean the element replaces all of .class1's styles with .fr .class1's styles. Instead, it looks at .fr .class1 for styles first, then .class1. This is "obvious" but this was why I was running into difficulty.

My goal was to remove styles by using .fr .class1's precedence over .class1. In order to do this, I realized I need to set values to 0 or neutral values:

Ejemplo)

.fr .class1 {
  font-size: 12px;
  line-height: 0;
  height: auto;
}

Otherwise, it will cascade to .class1 and fill these styles in.

preguntado el 28 de agosto de 11 a las 03:08

have you tried? best to try first...! -

@Cubed: But given the history of browser bugs it is best to check the standard and then try it to make sure the browsers you care about follow the standard in the ways you need them to. -

Added commentary in an edit to the original post. -

As you've found out, CSS applies styles for each property independently, so sometimes re-setting the original value is neccessary. To facilitate this, CSS3 introduced the initial palabra clave. -

Didn't know that existed. Thanks! -

3 Respuestas

Si desde .fr .class1 references two class names and .class1 only references one, the first is more specific. The rules in the CSS standard are aquí.

Respondido 28 ago 11, 07:08

Yes because the first example has Digital XNUMXk class names compared to uno.

Ejemplo: http://jsfiddle.net/jasongennaro/yQvAF/

Try using this CSS specificity calculator: http://www.suzyit.com/tools/specificity.php

Respondido 28 ago 11, 07:08

En respuesta a la edición:

CSS applies the values to each property individually. Block grouping does not matter. So

.fr .class1 {
  font-size: 12px;
}

.class1 {
  font-size: 12px;
  line-height: 18px;
  height: 80px;
}

es el mismo que

.fr .class1 {
  font-size: 12px;
}
.class1 {
  font-size: 12px;
}
.class1 {
  line-height: 18px;
}
.class1 {
  height: 80px;
}

tal como .fr .class1 es más específico que .class1 alone, is the same as

.fr .class1 {
  font-size: 12px;
}
.class1 {
  line-height: 18px;
}
.class1 {
  height: 80px;
}

Respondido 28 ago 11, 11:08

Precisely what I eventually discovered. Thanks for outlining this so clearly! - djreed

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.