1 reply [Last post]
ket
ket's picture
Offline
newbie
Last seen: 8 years 20 weeks ago
Timezone: GMT-7
Joined: 2014-02-28
Posts: 1
Points: 2

I have a div on a page with a background color. Based on user actions I want to change the background color. My approach was to use jQuery to add a class with just the new background color. It didn't work. So I tried an experiment. Here is the code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
.base {
	background-color:grey;
	height:100px;
	width: 200px;
	border: solid black 2px;
	color: white;
	}
.blue {
	background-color:blue;
	}
.red {
	background-color:red;
	}
</style>
</head>
 
<body>
<div class="base">
#1 base
</div>
<div class="base blue">
#2 base blue
</div>
<div class="base red">
#3 base red
</div>
<div class="base blue red">
#4 base blue red
</div>
<div class="base red blue">
#5 base red blue
</div>
</body>
</html>

When I run this in Firefox both box #4 and box #5 are red. I had hoped that the last class in the list (or the last added by jQuery) would take precedence.

So, the basic question is: If an element has multiple classes assigned and the same attribute has different values in different classes, how is order of precedence determined?

gary.turner
gary.turner's picture
Offline
Moderator
Dallas
Last seen: 1 year 22 weeks ago
Dallas
Timezone: GMT-6
Joined: 2004-06-25
Posts: 9776
Points: 3858

Not sure I'll be clear on

Not sure I'll be clear on this, but here goes nothing.

When multiple elements have the same specificity, but conflicting rules, the last style rule will take precedence.

In your example, the order of rules is base, blue, red. Where the element has both the blue and red classes, and there is a conflict (background-color) then it will read and apply the blue class, then it will read and apply the red class, overriding the blue's background color.

This is a feature. For example, I can have a base style sheet that is loaded first and has, say, the font set as sans-serif. Then another page can load a different stylesheet after the base stylesheet that sets the font as monospace. That second page will have a monospace font-family simply because of the order of the rule-sets.

Your solution, if you're using scripting is to have the script remove the conflicting class.

cheers,

gary

If your web page is as clever as you can make it, it's probably too clever for you to debug or maintain.