nth-of-type vs nth-child

后端 未结 7 1000
梦谈多话
梦谈多话 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
    
    
    
         
            
            
            
              

    This is paragraph in first div

    This is a paragraph

    This is paragraph in second div

    • First Item
    • Second Item
    **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
    
    
    
    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 :
    
    
    
         
                
                    
                
                
                  

    This is paragraph in first div

    This is a paragraph

    This is paragraph in second div

    • First Item
    • Second Item
    **And Final output will look like this**

提交回复
热议问题