【发布时间】:2015-10-16 01:51:55
【问题描述】:
我尝试使用 :nth-child(n),但效果不佳,我是否在错误的元素上使用了此选择器? 在具有以下类 block_photo 的元素 div 上。
.block_photo:first-child, .block_video:first-child {
margin-left:0px;
}
【问题讨论】:
标签: css css-selectors
我尝试使用 :nth-child(n),但效果不佳,我是否在错误的元素上使用了此选择器? 在具有以下类 block_photo 的元素 div 上。
.block_photo:first-child, .block_video:first-child {
margin-left:0px;
}
【问题讨论】:
标签: css css-selectors
您的 html 标记如下:
<section class="new photos">
<h4 class="title">...</h4>
<div class="block-photo">...</div>
<div class="block-photo">...</div>
...
</section>
匹配第一个子元素。
.block_photo:first-child {
/* styles here apply to the .block_photo IF it is the first child */
}
在您的情况下,因为第一个孩子是 <h4>,所以选择器 .block_photo:first-child 不匹配任何元素。
匹配某个类型的第一个元素
.block_photo:first-of-type {
/* styles here apply for the first .block_photo element */
/* that is what you need */
}
参考文献:
W3C specification on first-child
W3C specification on first-of-type
【讨论】:
first-of-type 解决方案,请参阅编辑。