如何将css属性添加到具有特定类名的第一个div?

时间:2013-06-04 19:22:22

标签: css css-selectors

我正在尝试使用“单位”类为第一个<div>添加下限。

<div id="wrapper-related-albums">
   <div class="header">...</div>
   <div class="unit">...</div> //add margin-bottom to this one!!!!
   <div class="header">...</div>
   <div class="unit">...</div>
</div>



#wrapper-related-albums .unit:first-child {margin-bottom:20px;} // doesn't work!!!
#wrapper-related-albums .unit:first-of-type {margin-bottom:20px;} // doesn't work!!!

2 个答案:

答案 0 :(得分:4)

更多通用/灵活解决方案

Wesley的答案非常适合您的特定html标记,因为它假设.unit将成为列表中的第二个元素。所以在你的情况下,可能是这样,他的解决方案运作良好。但是,如果有人在寻求更通用的解决方案,那么应该采取以下措施:

#wrapper-related-albums .unit { 
    /* code for the first one */ 
    margin-bottom: 20px;
}
#wrapper-related-albums .unit ~ .unit { 
    /* code for all the following ones */ 
    margin-bottom: 0px;
}

使用这样的通用兄弟选择器(~)将覆盖除第一个.unit之外的所有选择,允许第一个.unit位于包装器中的任何位置(不仅仅是位置#2) ,并且不需要事先知道位置)。 Here's a fiddle that illustrates it using a color change.

答案 1 :(得分:2)

有几种选择,具体取决于你的标记:

第二个有班级单元的孩子:

#wrapper-related-albums .unit:nth-of-type(2) { }
#wrapper-related-albums .unit:nth-child(2) { }

第一个元素的相邻兄弟(带有类单位):

#wrapper-related-albums :first-child + .unit {  }

我不相信有任何方法可以简单地选择“第一个.unit”,但您可以将余量添加到所有除了最后一个,如果它总是落在最后:

#wrapper-related-albums .unit { margin-bottom: 20px; }

/* negate the above rule */
#wrapper-related-albums .unit:last-child { margin-bottom: 0px; }