代码之家  ›  专栏  ›  技术社区  ›  GregH

什么CSS选择器可以用来选择另一个div中的第一个div

  •  81
  • GregH  · 技术社区  · 14 年前

    <div id="content>
    
       <h1>Welcome to Motor City Deli!</h1>
       <div style=" font-size: 1.2em; font-weight: bolder;">Sep 19, 2010</div>
       <div > ... </div>
    

    第二个div(“content”div中的第一个div)的css选择器是什么,以便我可以在该div中设置日期的字体颜色?

    4 回复  |  直到 10 年前
        1
  •  249
  •   Jeremy Moritz Igal S.    11 年前

    对你的问题最正确的答案是。。。

    #content > div:first-of-type { /* css */ }
    

    另一种选择:

    #content > div:nth-of-type(1) { /* css */ }
    
        2
  •  23
  •   BoltClock    13 年前

    你想要什么

    #content div:first-child {
    /*css*/
    }
    
        3
  •  16
  •   Stan Rogers    14 年前

    如果我们可以假设H1总是在那里,那么

    div h1+div {...}
    

    但是不要害怕指定content div的id:

    #content h1+div {...}
    

    这就相当于您现在不需要借助jQuery这样的JavaScript库就可以获得跨浏览器的性能。使用h1+div可以确保只有h1之后的第一个div获得样式。也有其他选择,但它们依赖于CSS3选择器,因此在大多数IE安装中不起作用。

        4
  •  5
  •   Josh Leitzel    14 年前

    :first-child pseudoclass ; 不幸的是,这将不适用于您的情况,因为您有一个 <h1> <div>s . 我建议你要么在 <div> ,就像 <div class="first">

    $('#content > div:first')