对同一个类中的不同元素应用不同的css

时间:2013-09-05 10:18:28

标签: css3

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

e.g。我有<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;
}

1 个答案:

答案 0 :(得分:1)

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

您只需使用id选择器:

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

如果您想按班级指定,那么假设<li>的班级为className,您可以使用多个伪选择器来访问孩子

DEMO: 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;
}
相关问题