Is it possible to give one CSS class priority over another?

Viewed 109806

Say I have a div that uses two css classes that both use text-align, but one is centered and the other is right aligned.

Is it possible to specify something that will give one class priority over the other?

6 Answers

as “meder omuraliev” has answered, you may use a more specified selector. and I would like to provider a general way that how to sepcific a higher priority for any type of selector, that is use the attr presdeo.

for example:

html body .foo { font-family: Arial !important;}
html body .bar[attr]{ font-family: Arial !important;}

to override this you may use like this:

html body .foo:not([NONE_EXISTS_ATTR]){ font-family: Consolas !important;}
html body .bar[attr]:not([NONE_EXISTS_ATTR]){ font-family: Consolas !important;}

To add to the other answers, you don't need to add selectors not related to what you originally wanted to increase specificity, the same can be achieved by repeating the same selector multiple times:

.foo.foo takes precedence over .foo, and .foo.foo.foo takes precedence over the previous ones.

This is better than adding non-related selectors, because you only select what you really want to select. Otherwise you might get unexpected behaviour when unrelated stuff you added changes.

.bar { text-align: right !important;}
Related