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

标签 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!!!

最佳答案

更通用/灵活的解决方案

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/

相关文章:

css - 定位 CSS 类的第二个实例

css - 如果元素在包装元素内,如何使 CSS div 宽度等于浏览器宽度

html - 当我将图像与跨度内联时,为什么我的图像会被下推?

html - 如何连续构建具有两个不同对象的延迟循环动画?

html - 将图像放在标题中(同一行)

css - 在 twiiter-bootstrap 中使用带选择的输入组的替代标准代码

html - 在 HTML 中选择 td 元素值的 css-selector 路径是什么?

css - 使用 css 选择器禁用与复选框关联的标签

css3 nth-child 特异性

CSS 下一个元素(无兄弟)选择器