How to override the properties of a CSS class using another CSS class

user3075049 picture user3075049 · Jan 6, 2014 · Viewed 335.8k times · Source

I am fairly new to CSS3 and I want to be able to do the following:

When I add a class into a an element, it overrides the properties of another class used in this specific element.

Let's say that I have

<a class="left carousel-control" href="#carousel" data-slide="prev">

I want to be able to add a class called bakground-none, that will over override the default background in the class left.

Thanks!

Answer

Jukka K. Korpela picture Jukka K. Korpela · Jan 6, 2014

There are different ways in which properties can be overridden. Assuming you have

.left { background: blue }

e.g. any of the following would override it:

a.background-none { background: none; }
body .background-none { background: none; }
.background-none { background: none !important; }

The first two “win” by selector specificity; the third one wins by !important, a blunt instrument.

You could also organize your style sheets so that e.g. the rule

.background-none { background: none; }

wins simply by order, i.e. by being after an otherwise equally “powerful” rule. But this imposes restrictions and requires you to be careful in any reorganization of style sheets.

These are all examples of the CSS Cascade, a crucial but widely misunderstood concept. It defines the exact rules for resolving conflicts between style sheet rules.

P.S. I used left and background-none as they were used in the question. They are examples of class names that should not be used, since they reflect specific rendering and not structural or semantic roles.