Why doesn't nth-of-type/nth-child work on nested elements?

前端 未结 1 1613
别跟我提以往
别跟我提以往 2020-11-22 06:09

I\'m trying to change the style of odd divs that are inside a div. For some reason the nth-of-type(odd) is affecting all my divs when it\'s inside another div.

1条回答
  •  情话喂你
    2020-11-22 06:45

    :nth-of-type() is similar to :nth-child() in that they must all be from the same parent. If you need those wrapper divs, use :nth-of-type() on those wrappers instead:

    div.post:nth-of-type(odd) .video-entry-summary {
        width:214px; 
        height:210px; 
        margin-left:0px;
        float:left;
        position:relative; 
        overflow:hidden; 
        border:1px solid black; 
        background:#ccc; 
    }
    

    If all the siblings are .post, use :nth-child() instead to prevent confusion with what :nth-of-type() really means:

    .post:nth-child(odd) .video-entry-summary {
        width:214px; 
        height:210px; 
        margin-left:0px;
        float:left;
        position:relative; 
        overflow:hidden; 
        border:1px solid black; 
        background:#ccc; 
    }
    

    .video-entry-summary {
      width: 214px;
      height: 210px;
      margin-left: 10px;
      float: left;
      position: relative;
      overflow: hidden;
      border: 1px solid black;
    }
    
    .post:nth-child(odd) .video-entry-summary {
      width: 214px;
      height: 210px;
      margin-left: 0px;
      float: left;
      position: relative;
      overflow: hidden;
      border: 1px solid black;
      background: #ccc;
    }
    video 1
    video 2
    video 3
    video 4

    0 讨论(0)
提交回复
热议问题