什么是适当的CSS选择器来选择类中的第一个div或具有特定的id?使用父/子元素这似乎更容易,但我没有找到任何简单元素.
更新:解决方案
我找到的最干净,最兼容的解决方案是.class~ .class,它选择跟在前一类之后的所有后一类.例如,如果要从其类中的第一个元素中删除顶部边框,您将:
<style>
.dolphin {
border-top:0;
}
.dolphin ~ .dolphin {
border-top:1px solid #000;
}
</style>
Run Code Online (Sandbox Code Playgroud)
use*_*515 30
如果要div在特定类中选择第一个,则可以使用:
.class div:first-child
Run Code Online (Sandbox Code Playgroud)
但是,当您获得以下HTML时,这将不起作用:
<div class="class">
<h1>The title</h1>
<div>The CSS won't affect this DIV</div>
</div>
Run Code Online (Sandbox Code Playgroud)
它不会起作用,因为div它不是第一个孩子.class.如果您div不想在这种情况下定位,我建议添加另一个容器(或者添加一个类,div无论你喜欢什么:))
要选择类中的第一个div,我建议使用此方法
.yourClassName > div:first-child{
// Your properties
}
Run Code Online (Sandbox Code Playgroud)
同样如果你想在id中选择就行了
#yourUniqueId > div:first-child{
// Your properties
}
Run Code Online (Sandbox Code Playgroud)
但是如果你有一个id,你应该只有一个,否则你会编码无效的 HTML,只需使用这样的简单选择器为id的
#yourID{
// Your Properties
}
Run Code Online (Sandbox Code Playgroud)
另请注意,在@ sourcecode的回答中,他目前没有>在他的例子中没有它,它不会选择一个类中的第一个div,而是选择该类中的每个第一个div检查这个小提琴的示例那
这是我的答案的演示