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

4

我正在尝试为第一个带有类名 "unit" 的 <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!!!

它有一个ID。为什么不使用它? - John Conde
:first-of-type 只能在元素选择器上工作,不能在类上工作。为什么需要在此元素中添加底部边距? - cimmanon
:first-of-type 查找其父元素的子元素列表中,是其类型的第一个同级元素;而 :first-child 则表示某个其他元素的第一个子元素——属性会被忽略。 - Adrift
使用 #wrapper-related-albums div.unit,它们都会获得一个边距... 我只想要 div.wrapper-related-albums 的第一个 .unit。 - Marco
2个回答

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位置,也无需事先知道位置)。这里有一个演示如何使用color更改的fiddle。

2

根据您的标记,有几个选项:

第二个带有类“unit”的子元素:

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

第一个元素的相邻兄弟元素(带有class为unit):

#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; } 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接