祖父母的第一个孩子

Mos*_*she 5 html css

我在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加下划线.救命?

pra*_*war 5

.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)


Tim*_*Tim 3

使用:

.box > div:first-child > h1 {
    text-decoration: underline;
}
Run Code Online (Sandbox Code Playgroud)

请注意,first-child应用于div而不是h1标签。

  • 仅当“h1”位于第一个“div”中时,这才有效。如果不是怎么办? (2认同)