Marko
Marko

Reputation: 1487

Overriding css values

Sometimes when I declare a value for something, and later I want to override it with different value it doesn't work. For example (sass styling):

.wrapper-breadcrumbs {
    h1.breadcrumb-title {
        font-size: 46px;
    }
}

And just below I put this...

@media (max-width: 768px) {
    h1.breadcrumb-title {
        font-size: 32px;
    }
}

... it won't work, and I see in Chrome element inspection that the first one actually overrode the second value, even though the second statement is below first. But if I repeat parent class names like this...

@media (max-width: 768px) {
    .wrapper-breadcrumbs h1.breadcrumb-title {
        font-size: 32px;
    }
}

Then it works! For me it seems strange... is there any rule for this? Am I missing something? Why do I have to write parent class name?

Upvotes: 1

Views: 68

Answers (2)

Ismail Zafar
Ismail Zafar

Reputation: 174

It is due to first selector has higher precedent than second selector. Like Id selector has higher precedent than class selector. So if you apply any style using id selector and later own try to override it with class selector than it won't work.

.wrapper-breadcrumbs {
    h1.breadcrumb-title {
        font-size: 46px;
    }
}

In this case you have two class and one attribute selector so its precedent is following.

precedent = (inline, id, class, element/ pseudo)

precedent = (0,0,2,1) //Left element has more precedent than right element.

@media (max-width: 768px) {
    h1.breadcrumb-title {
        font-size: 32px;
    }
}

precedent = (0,0,1,1)

You can clearly see that first has more precedence than second selector so it will never work.

@media (max-width: 768px) {
    .wrapper-breadcrumbs h1.breadcrumb-title {
        font-size: 32px;
    }
}

precedent = (0,0,2,1)

In this case it has same precedence as first element so it will overwrite the previous style and will work on this data.

You can use following link to calculate precedence of CSS selectors.

http://specificity.keegan.st/

Always try to overcome this problem by managing of the precedence of the selector instead of placing !important with CSS styling as it will override default precedence of selectors and in case of huge CSS make it difficult to debug it.

Upvotes: 2

Bohuslav Burghardt
Bohuslav Burghardt

Reputation: 34766

It's because the first rule has higher specificity (2 classes and 1 element) vs 1 class and 1 element for the second rule.

The second rule needs to have same or higher specificity to override the first one. I recommend to take a look at Specifics on Specificity article on CSS tricks for more details.

As mentioned in the comments, you can also put !important after the font-size in the second rule, however that is typically a very bad practice and you should modify your CSS rule to have higher specificity instead, which is cleaner and will help you avoid headaches when debugging your CSS :)

Upvotes: 4

Related Questions