nth-of-type vs nth-child

后端 未结 7 1017
梦谈多话
梦谈多话 2020-11-22 02:30

I am a bit confused about the nth-of-type pseudo class, and how this is supposed to work - especially as compared to the nth-child class.

M

相关标签:
7条回答
  • 2020-11-22 03:28
    element:nth-of-type(p) //p=integer , basically return the DOM Element with respect of body.
    Let us understand this with an example
    
    
    
         <html>
            <head>
            </head>
            <body>
              <div>
                <p> This is paragraph in first div</p>
               <input type="text" placeholder="Enter something"/>
                <p>This is a paragraph </p>
              </div>
              <div>
                <p>This is paragraph in second div</p>
                <ul>
                <li>First Item</li>
                <li>Second Item</li>
                <li>
                 <label> This is label <strong>inside Unordered List</strong></label>
                </li>
    
              </ul>
    
               </div>
            </body>
        </html>
    
    
    **This above html will look like this.**
    

    Now suppose We have to style Second Item in UnOrderd list.
    In this case we can use nth-of-type(index) selector wrt DOM body.
    
    we can achieve styling like this
    
    <style type="text/css">
                    div:nth-of-type(2) li:nth-of-type(2){
                        color: red;
                        font-weight: bold;
                    }
                </style>
    
    explanation : div:nth-of-type(2) by this we are trying to tell find the second div in html body,after that we have second div accessible ,now we can dig inside div using same nth-of-type selector,next we are using li:nth-of-type(2) so now we can find second list inside second div and styling it .
    
    Final Code :
    
    
    
         <html>
                <head>
                    <style type="text/css">
                        div:nth-of-type(2) li:nth-of-type(2){
                            color: red;
                            font-weight: bold;
                        }
                    </style>
                </head>
                <body>
                  <div>
                    <p> This is paragraph in first div</p>
                   <input type="text" placeholder="Enter something"/>
                    <p>This is a paragraph </p>
                  </div>
                  <div>
                    <p>This is paragraph in second div</p>
                    <ul>
                    <li>First Item</li>
                    <li>Second Item</li>
                    <li>
                     <label> This is label <strong>inside Unordered List</strong></label>
                    </li>
    
                  </ul>
    
                   </div>
                </body>
            </html>
    
    **And Final output will look like this**
    

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