CSS Child vs Descendant selectors

前端 未结 8 2011
心在旅途
心在旅途 2020-11-22 03:36

I am a bit confused between these 2 selectors.

Does the descendent selector:

div p

select all p withi

相关标签:
8条回答
  • 2020-11-22 03:45

    CSS selection and applying style to a particular element can be done through traversing through the dom element [Example

    Example

    .a .b .c .d{
        background: #bdbdbd;
    }
    div>div>div>div:last-child{
        background: red;
    }
    
    <div class='a'>The first paragraph.
     <div class='b'>The second paragraph.
      <div class='c'>The third paragraph.
       <div class='d'>The fourth paragraph.</div>
       <div class='e'>The fourth paragraph.</div>
      </div>
     </div>
    </div>
    
    0 讨论(0)
  • 2020-11-22 03:53

    Yes, you are correct. div p will match the following example, but div > p will not.

    <div><table><tr><td><p> <!...
    

    The first one is called descendant selector and the second one is called child selector.

    0 讨论(0)
  • 2020-11-22 03:55

    Bascailly, "a b" selects all b's inside a, while "a>b" selects b's what are only children to the a, it will not select b what is child of b what is child of a.

    This example illustrates the difference:

    div span{background:red}
    div>span{background:green}
    
    <div><span>abc</span><span>def<span>ghi</span></span></div>
    

    Background color of abc and def will be green, but ghi will have red background color.

    IMPORTANT: If you change order of the rules to:

    div>span{background:green}
    div span{background:red}
    

    All letters will have red background, because descendant selector selects child's too.

    0 讨论(0)
  • 2020-11-22 03:56

    In theory: Child => an immediate descendant of an ancestor (e.g. Joe and his father)

    Descendant => any element that is descended from a particular ancestor (e.g. Joe and his great-great-grand-father)

    In practice: try this HTML:

    <div class="one">
      <span>Span 1.
        <span>Span 2.</span>
      </span>
    </div>
    
    <div class="two">
      <span>Span 1.
        <span>Span 2.</span>
      </span>
    </div>
    

    with this CSS:

    span { color: red; } 
    div.one span { color: blue; } 
    div.two > span { color: green; }
    

    http://jsfiddle.net/X343c/1/

    0 讨论(0)
  • 2020-11-22 03:57

    div > p matches ps that have a div parent - <div><p> in your question

    div p matches ps that have a div ancestor (parent, grandparent, great grandparent, etc.) - <div><p> and <div><div><p> in your question

    0 讨论(0)
  • 2020-11-22 03:59

    Just think of what the words "child" and "descendant" mean in English:

    • My daughter is both my child and my descendant
    • My granddaughter is not my child, but she is my descendant.
    0 讨论(0)
提交回复
热议问题