0

我想知道是否可以为同一类中的不同元素应用不同的 css 设置。

例如,我有<li>并且我想对#city、#state 和#zipcode 应用不同的前景色,但我想在同一个类中实现这一点。

<li>
 <div id="city">    </div>
 <div id="state"> </div>    
 <div id="zipcode"></div>
</li>

我想要类似的东西 -

.className{
     here is css for city;
     here is css for state;
     here is css for zipcode;
}
4

1 回答 1

1

我真的不知道你为什么要这样做。

您可以简单地使用id选择器:

#city    { background-color: red;   }
#state   { background-color: green; }
#zipcode { background-color: blue;  }

如果你想按类指定,那么假设你<li>有一个类,className你可以使用许多伪选择器来访问孩子

演示:http: //jsfiddle.net/8qAvb/

HTML

<li class="className">
    <div id="city">city</div>
    <div id="state">state</div>
    <div id="other1">other1</div>
    <div id="other2">other2</div>
    <div id="other3">other3</div>
    <div id="other4">other4</div>
    <div id="zipcode">zipcode</div>
</li>

CSS

.className > div {
    background-color: green;
}
.className > div:first-child {
    background-color: red;
}
.className > div:nth-child(3) {
    background-color: lime;
}
.className > div:nth-child(4) {
    background-color: pink;
}
.className > div:nth-child(5) {
    background-color: orange;
}
.className > div:last-child {
    background-color: blue;
}
于 2013-09-05T10:29:38.453 回答