我在div中有多个div.我希望父div的第一个h1加下划线.first-child的问题是它查看了父div,在我的例子中是父错误.例如:
<div class="box">
<div><h1>first h1 needs to be underlined</h1></div>
<div>bla bla bla</div>
<div>bla bla bla2</div>
<div><h1>big bla bla bla but not underlined</h1></div>
</div>
Run Code Online (Sandbox Code Playgroud)
我只希望第一个h1加下划线但是使用.box h1:firstchild会导致h1加下划线.救命?
.box > div:first-of-type > h1:first-of-type{
text-decoration: underline;
}
Run Code Online (Sandbox Code Playgroud)
如果你有多个h1first ,div它只会在first 下划线h1。只是添加到蒂姆斯的答案
更新 JQuery 解决方案以在任何第一个 div 中为 h1 下划线
var h1Found = false;
$( ".box > div " ).each(function( index ) {
$(this).find("h1").each(function(){
if(h1Found) return false;
$(this).css("text-decoration", "underline" );
h1Found = true;
})
});
Run Code Online (Sandbox Code Playgroud)
使用:
.box > div:first-child > h1 {
text-decoration: underline;
}
Run Code Online (Sandbox Code Playgroud)
请注意,first-child应用于div而不是h1标签。