【问题标题】:CSS selector first-child does not work [duplicate]CSS选择器第一个孩子不起作用[重复]
【发布时间】:2015-10-16 01:51:55
【问题描述】:

我尝试使用 :nth-child(n),但效果不佳,我是否在错误的元素上使用了此选择器? 在具有以下类 block_photo 的元素 div 上。

.block_photo:first-child, .block_video:first-child {
    margin-left:0px;
}

http://tmptstdays4god.ucoz.com/

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    您的 html 标记如下:

    <section class="new photos">
        <h4 class="title">...</h4>
        <div class="block-photo">...</div>
        <div class="block-photo">...</div>
        ...
    </section>
    

    第一个孩子/第n个孩子

    匹配第一个子元素。

    .block_photo:first-child {
        /* styles here apply to the .block_photo IF it is the first child */
    }
    

    在您的情况下,因为第一个孩子是 &lt;h4&gt;,所以选择器 .block_photo:first-child 不匹配任何元素。

    第一个类型/第 n 个类型

    匹配某个类型的第一个元素

    .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

    【讨论】:

    • 谢谢!更有意义。
    • 或创建一个父元素来容纳这些容器 .photo_block
    • 您也有first-of-type 解决方案,请参阅编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多