Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS child selector higher precedence than class selector?

I have the following HTML:

<div class="form-square">
     <div class="seven-col">
        Hello World!
      </div>
</div>

And the following CSS:

div.form-square > div {
    padding: 50px;
}

.seven-col {
    padding: 0;
}

Firefox and Firebug is using the first of the two CSS rules. How come "div.form-square > div" has higher precedence than ".seven-col" which is more specific?

like image 307
mrmclovin Avatar asked Aug 23 '11 12:08

mrmclovin


People also ask

Which CSS selector has the highest precedence?

Id selector has highest priority because of unique nature of the ID attribute definition. We have two classes with one ID selector here it will apply font-size:12px and font-weight:500 due to the specificity rule as ID selector has highest priority after inline CSS.

Which selectors have the highest priority?

Values defined as Important will have the highest priority. Inline CSS has a higher priority than embedded and external CSS. So the final order is: Value defined as Important > Inline >id nesting > id > class nesting > class > tag nesting > tag.

What is the correct priority order of selectors CSS?

When writing selectors, you should prioritize finding in this order: ID, name, class, or anything else that is unique to the element. Complex CSS selectors. XPath selectors.

Which selector has the strongest selector specificity?

ID selectors have the highest specificity amongst the CSS selectors: 1, 0, 0, 0. Because of the unique nature of the ID attribute definition, we are usually styling a really specific element when we call up the ID in our CSS. – The specificity is 1, 0, 0, 1 because we have a type selector and an ID selector.


1 Answers

div.form-square > div consists of 1 class selector + 2 type selectors (plus a child combinator).

.seven-col consists of 1 class selector.

The number of class selectors is equal, so the comparison is done in type selectors. The first selector has more type selectors so it is more specific.

Specificity is based on the number of each kind of selector in the entire thing, not for the part on the right hand side of the rightmost combinator.

(NB: The first example also has what CSS 2 calls a child selector, but that doesn't count towards specificity and describes a relationship between elements rather than a feature of an element, which probably why CSS 3 is renaming it to the child combinator).

like image 94
Quentin Avatar answered Nov 08 '22 07:11

Quentin