我的意思是,如果我有一个有两个div的页面,我想让每个div都有一个单独的样式,我该怎么做呢?
的例子:
div{ background: red;} // apply this style to one div.
div{ background: blue;} //apply this style to another div.
我意识到可以为每个div添加一个类,但是如果我扩展它呢?如果我想让页面中具有许多不同属性的整个部分使用样式表的一部分,而另一个整个部分使用另一部分,该怎么办?
你可以简单地在CSS规则的前面加上节的ID或类。例如:
#section1 h1 {
color: red;
}
#section2 h1 {
color: blue;
}
和#section1
或#section2
的前缀基本每个规则取决于包含部分。
据我所知,你想要的是每个div在你的头是绿色的,而每个div在你的脚应该是红色的。
#header div{ background-color: green; }
比和
<div id="header">
<div>I'm green</div>
</div>
您还可以使用更复杂的选择器来帮助您解决特殊情况,例如:
#header div{ background-color: red; }
#header > div{ background-color: green; }
比和
<div id="header">
<div>
I'm green...
<div>...and I'm red</div>
</div>
</div>
Microsoft对可用的选择器有一个很好的概述。有些例子有时有点弱,但它的东西。
你可以这样做:
.firstSectionType div{ background: red;} // apply this style to one div.
.firstSectionType span { color: blue; }
.secondSectionType div{ background: blue;} //apply this style to another div.
.secondSectionType span {color: red; }
如果你的HTML看起来像这样:
<div class="firstSectionType">
<p><span>Hello</span></p>
<div>This has a red background and <span>this is blue text</span></div>
</div>
<div class="secondSectionType">
<p><span>Hello</span></p>
<div>This has a blue background and <span>this is red text</span></div>
</div>
相应章节中的div
s和span
s将进行相应的格式化。
上面的CSS要求你在每个规则中重复.firstSectionType
或.secondSectionType
,但是像LESS这样的CSS预处理器将允许你重写它:
.firstSectionType
{
div{ background: red;} // apply this style to one div.
span { color: blue; }
}
.secondSectionType
{
div{ background: blue;} //apply this style to another div.
span {color: red; }
}