我正在尝试为第一个 <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!!!
最佳答案
更通用/灵活的解决方案
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.
关于css - 如何将 css 属性添加到具有特定类名的第一个 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16925835/