Cascading Parent-Child
我希望所有.box p颜色都是粉红色,但似乎所有在#container中的.box p都有红色。我希望级联会改变颜色,但我认为我犯了一个错误。Cascading Parent-Child
你能告诉我我错了吗?
感谢
/_ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ ____
<html>
<head>
<title> Buvbvn</title>
<style type="text/css">
p {color: #F00;}
/* container holds all visible page elements */
#container{
padding:20px;
border:20px solid #000;
background: #CCC;
}
.box{
margin: 10px;
padding:20px;
border: 1px solid #000;
}
/* Make text red only for paragraphs within the container */
#container p {
color: #F00;
}
/* Make text pink only for paragraphs within the box class */
.box p {
color: #FF00FF;
}
</style>
</head>
<body>
<div id ="container">
<p>This is our content area.</p>
<div class = "box">
<p >I'm in a box!</p>
</div>
<div class = "box">
<p >I'm also in a box!</p>
</div>
</div>
<div class = "box">
<p >I'm also in a box!</p>
</div>
</body>
的问题不是级联,这是选择的特异性。基于id
的选择器比基于class
的选择器更具体。
您当前的代码产生了这样的结果:JS Fiddle demo。
要修改,这么一个.box
内的所有段落都是粉红色的,你可以删除从选择的id
,只具有p
,或类添加到选择,给:#content .box p
:
#container .box p, /* addresses those paragraphs inside a .box that's inside #container */
.box p { /* addresses those paragraphs inside a .box, but not necessarily the #container */
color: #FF00FF;
}
将这个:
.box p {
color: #FF00FF !important;
}
虽然这样做有效,但重要的是要记住'!important'正在拿大锤来破解核桃。从长远来看,修改选择器通常更容易......(这不**代表倒票,只是(有希望)建设性的批评)。 – 2011-04-23 16:16:41
@大卫我听到你。谢谢 – locrizak 2011-04-23 16:32:27
我建议:你想用一个类中的所有元素有粉红色文字
p {
color: #F00; /* Red */
}
.box p {
color: #F0F; /* Pink */
}
做什么? – Maverick 2011-04-23 16:12:12