Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Priority on css classes

Tags:

html

jquery

css

I have a span with 2 classes, like this <span class="tag invalid_tag">abc</span>. I add the second class through jQuery correctly and i need the properties from the second class to override the first, without actually removing it. For instance, the properties are the font color and background-color. Usually the tag is green but when i add the class "invalid_tag" it should turn red but it doesn't because the first class has the priority. I would like to know how to change this priority, or if i can achieve this in a different way.

like image 383
Chobeat Avatar asked Dec 07 '25 08:12

Chobeat


1 Answers

The priority of CSS declarations relies on their order in the CSS (later declarations override earlier ones) and their specificity (more specific declarations override less-specific ones). (It has nothing to do with the order you specify the class names in the attribute.) More in Section 6 the specification.

Here's an example of order. This CSS

.foo {
    color: red;
}
.bar {
    color: blue;
}

with this HTML

<p class="foo bar">Hi there</p>
<p class="bar foo">Hi again</p>

...results in two blue paragraphs, because the second declaration takes precedence over the first. (Live example) That happens because both declarations have the same specificity.

Here's a demonstration of specificity:

This CSS

p.foo {
    color: red;
}
.bar {
    color: blue;
}

...with the same HTML results in two red paragraphs, because the selector p.foo is more specific than the selector .bar, so it takes precedence even though it's earlier in the CSS. (Live example)

like image 127
T.J. Crowder Avatar answered Dec 08 '25 22:12

T.J. Crowder