有选择地将样式表应用于div

时间:2014-08-07 17:39:48

标签: html css html5

我正在尝试使用多个div进行简单的网页设计。每个div应该从列表中应用一个或多个外部样式表。

我的问题是,从我到目前为止阅读的例子来看,我不确定如何做到这一点优雅。外部样式表似乎应用于整个html文件。那么我应该将模块化模块化为单独的文件吗?或者像iFrame这样的东西是一个更简洁的解决方案吗?

当前解决方案:
外部CSS:

div.test1 {
    color: purple;
    background-color: #d8da3d
}

.test2 {
    color: red;
    background-color: #d8da3d
}

#test3{
    color: green;
    background-color: #d8da3d
}

HTML正文代码:

<div class="test1">
    <p> Style1
</div>

<div class="test2">
    <p> Style2
</div>

<div id="test3">
    <p> Style3
</div>

我的推荐:
Div with external stylesheet?
http://www.htmlhelp.com/reference/css/style-html.html

3 个答案:

答案 0 :(得分:1)

您是否只是尝试以不同的方式设计div?你有没有考虑过为每个div使用一个类?

从您提供的第二个链接:http://www.htmlhelp.com/reference/css/style-html.html#class

答案 1 :(得分:1)

使用css样式时:

body{
 color:purple;
 background-color: #d8da3d
}

您说要使用您设置的样式设置文档的整个主体样式。

为了定位特定元素,您应该为这些元素提供 id

例如:

<div id="test1"></div>
<div class="testing"></div>
<div class="testing"></div>

请注意,使用和 id 时,您必须确保为该元素指定唯一ID。但是,许多元素可以共享相同的。因此,对于上面的示例样式:

#test1{
  color:blue;
  background-color:black;
}
.testing{
  color:red;
  background-color:white;
}

将第一个样式(test1)应用于具有相同id的div,将第二个样式(test)应用于具有相同类的两个div。

答案 2 :(得分:1)

- 1

看看这个: https://stackoverflow.com/a/17668004/1552518

- 2

或者只是为每个div添加一个类:

<div id="container">
    <div class='div1'>
        style1
    </div>
    <div class='div2'>
        Style2
    </div>
</div>

在你的外部css中:

.div1 {
    // Style applied only to the first div
}


.div2 {
    // Style applied only to the second div
}

- 3

或者如果你不能在div中添加一个类,请在css中使用它:

#container > div:first-child {
    // Style applied only to the first div
}


#container > div:last-child {
    // Style applied only to the second div
}