Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does CSS priority work?

Tags:

html

css

Let's say I have the following HTML:

<span id="id1" class="class1 class2">This is a test</span>

and if #id1, .class1 and .class2 all have different sets of mutually exclusive CSS rules, which one wins? I have been testing an example and in one case it's choosing (I think) the one that is listed at the bottom of the CSS file, but in another case it seems non-deterministic.

Is there a specific rule in this case?

like image 695
leora Avatar asked Oct 29 '25 22:10

leora


1 Answers

The basic principle of cascading in CSS is that you have one element, and one or more CSS rules that apply to the same element (because the element matches their selectors). In this process, all applicable styles are computed, with any conflicts resolved (or cascaded), and then, well, applied.

If the rules and their declarations are mutually exclusive, then none of them "wins" over any of the others per se, since there's no conflict to resolve and therefore nothing to override. For example, if you have these rules:

#id1 {
    color: red;
}

.class1 {
    border-width: 1px;
}

.class2 {
    border-style: dashed;
}

Then your element will have red text and a dashed red border that's 1 pixel thick. There are no conflicts, so all of them will combine in effect. (Note that the border is red due to special behavior.)

jsFiddle preview

It's only when you have the same property declared in more than one rule that selector specificity and cascading become relevant, because then you'd need to override values for that same property. In that case, then as already mentioned IDs take precedence over classes and equally-specific rules are applied from the top down; read about selector specificity.

For example, if you have these rules:

#id1 {
    color: red;
}

.class1 {
    text-decoration: underline;
    color: green;
}

.class2 {
    text-decoration: none;
    color: blue;
}

Then your element will have red text with no decoration, because

  • the color value in #id1 overrides that in both classes, and

  • the text-decoration value in .class2 overrides that in .class1.

jsFiddle preview

Remember that all this has to apply to the same element. If you have a parent that only has an ID, with a child that only has a class, then none of this will apply because you're dealing with entirely separate elements. What comes into play instead is inheritance, which is also covered in the document I link to above.

like image 101
BoltClock Avatar answered Nov 01 '25 12:11

BoltClock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!