CSS选择器:ID或类中的第一个div [英] CSS selector: first div within an id or class

查看:1306
本文介绍了CSS选择器:ID或类中的第一个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

选择一个类或具有特定ID的第一个div的正确CSS选择器是什么?对于父元素/子元素来说,这似乎要容易得多,但对于简单元素,我还没有发现任何东西。

What is the proper CSS selector to select the first div within a class or with a specific id? This seems to be much easier with parent/child elements but I haven't found anything for simple elements.

更新:解决方案

我发现的最干净,最兼容的解决方案是.class〜.class,它选择所有跟随前一类的后一类。例如,如果您要删除其类中第一个元素的顶部边框,则可以:

The cleanest, most compatible solution I found was .class ~ .class which selects all the latter classes that follow the former class. For example, if you wanted to remove the top border from the first element within its class you would:

<style>
    .dolphin {
        border-top:0;
        }
    .dolphin ~ .dolphin {
        border-top:1px solid #000;
        }
</style>


推荐答案

如果要选择第一个 div 在特定类中,则可以使用:

If you want to select the first div within a specific class then you can use:

.class div:first-child

但是,当您具有以下HTML时,此方法将无效:

This however won't work when you've got the following HTML:

<div class="class">
    <h1>The title</h1>
    <div>The CSS won't affect this DIV</div>
</div>

它不起作用,因为 div 不是 .class 的第一个孩子。如果在这种情况下,您不想定位 div ,则建议添加另一个容器(或向 div 任何您喜欢的:))

It won't work because the div isn't the first child of the .class. If you wan't to target that div in this case I'd suggest adding another container (or adding a class to that div whatever you like :) )

这篇关于CSS选择器:ID或类中的第一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆