nth-child doesn't respond to class selector

后端 未结 3 794
生来不讨喜
生来不讨喜 2020-12-01 09:04

Unless it\'s not supposed to but I can\'t seem to get nth-child to acknowledge the class selector.

I have say 4 divs inside another div, all of various c

相关标签:
3条回答
  • 2020-12-01 09:41

    This is an old post but I ended up here seeking for an answer for similar problem. Perhaps this will help someone.

    I had the following structure, wanting to select the n-th "foo"-div:

    <body>
      <div class='container'>
        <div class='foo'></div>
      </div>
      <div class='container'>
         <div class='foo'></div>
      </div>
      <div class='container'>
         <div class='foo'></div>
      </div>
      <div class='container'>
         <div class='foo'></div>
      </div>
    </body>
    

    The trick was "go back" and select the parent element with repeated siblings, in this case .container and then select its child(ren):

    .container:nth-of-type(3) .foo {
        styles here
    }
    
    0 讨论(0)
  • 2020-12-01 09:43

    Try the :nth-of-type() pseudo-selector instead:

    #content .foo:nth-of-type(1) { margin-top: 0; }
    

    Note that :nth-of-type() counts the elements with the same name. So .foo:nth-of-type(1) will not select the first element with the class foo but any first element that is the first in the list of elements grouped by the same name. If you have some document like this:

    <div>
        <i class="foo">1</i><i>x</i><i class="foo">2</i>
        <b class="foo">3</b><b>x</b><b class="foo">4</b>
    </div>
    

    .foo:nth-of-type(1) will select the elements <i class="foo">1</i> and <b class="foo">3</b> as both are the first of its own type.

    0 讨论(0)
  • 2020-12-01 09:52

    I think you're using the wrong selector, try:

    #content .foo:first-of-type { margin-top: 0; }
    
    0 讨论(0)
提交回复
热议问题