如何按类别分隔样式表?

时间:2013-01-14 08:49:05

标签: css

我的意思是,如果我有一个包含两个div的页面,并且我希望每个div都有一个单独的样式,那么我将以什么方式进行此操作?

示例:

div{ background: red;} // apply this style to one div.
div{ background: blue;} //apply this style to another div.

我意识到可以只为每个div添加一个类,但是如果我扩展它会是什么?如果我希望我的页面的整个部分有很多不同的属性来使用样式表的一部分,而另一部分要用另一部分呢?

3 个答案:

答案 0 :(得分:3)

您可以简单地在CSS规则前加上该部分的ID或类。例如:

#section1 h1 {
    color: red;
}

#section2 h1 {
    color: blue;
}

并且基本上为每个规则添加前缀#section1#section2,具体取决于包含的部分。

答案 1 :(得分:2)

据我所知,你希望你的标题中的每个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有great overview个可用的选择器。有些例子有时会有点弱,但有些东西。

答案 2 :(得分:1)

你可以这样做:

.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>

相应部分中的divspan将相应地进行格式化。

上面的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; }
}
相关问题