Reputation: 17
I've just started learning course on basic HTML & CSS. I've been studying priority when it comes to CSS selectors today. Now, we have the following exercise that we were walking, I was wondering if someone can help me understand why 1,2 and 3 are Red, Red and Green when it comes to their text colors. As far As I understand, an ID takes preference over a class which in turn is a higher priority than just a regular element. So shouldnt 2 be green because we're setting .central to be green?
Thanks
body {
color: blue;
background-color: yellow;
}
p {
color: red;
}
.central, .item {
color: green;
}
#item {
background-color: cyan;
}
<p>1</p>
<div class="central">
<p>2</p>
<ul>
<li id="item">3</li>
</ul>
</div>
Upvotes: 1
Views: 2765
Reputation: 201588
In the CSS model, every element has all properties defined in CSS specifications, such as the color
property. In your example, the element <p>2</p>
matches only one CSS rule, namely the one that sets the color
property to red
for p
element. Thus, regarding the color of “2”, there is priority issue to be resolved.
Whatever values are set on outer elements cannot possibly affect the color
property here.
Upvotes: 2
Reputation: 1485
You set green color for your div tag contents only. So it doesn't affect your paragraph tag contents because you mentioned color red for the paragraph.And also note your background color yellow for body doesn't affect because start of your style tag check out the below Markup:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>1</p>
<div class="central"><p class="central">2</p>
<ul>
<li id="item" >3</li>
</ul>
</div>
</body>
<style>
body {
color: blue;
background-color:yellow;
}
p {
color: red;
}
.central,.item{
color: green;
}
#item {
background-color: cyan;
}
</style>
Upvotes: 0
Reputation: 5834
First You correct Your Markup.
The style Priority is given From top to bottom. There is rule for id or class selectors.
Order of precedence of CSS Style Rules are:
1 User defined style
2 Embedded or inline style sheet
3 Internal style sheet
4 External style sheet
5 Browser default style
Upvotes: 1
Reputation: 27082
The second one is and should be red, it works correctly.
Everything in the .central
is green, but paragraphs are red.I created you a fiddle.
<div class="central">
green outside the <p>
<p>red paragraph</p>
</div>
<style>
p {color: red;}
.central {color: green;}
</style>
Of course, if you add a rule for paragraphs inside .central
, this rule will be applied.
<style>
.central p {color: blue} /* paragraph above will be blue, not red */
</style>
Upvotes: 0