CSS selectors ul li a {…} vs ul > li > a {…}

前端 未结 6 1290
执念已碎
执念已碎 2020-12-08 02:57
  1. What is the difference between ul > li > a {...} and ul li a {...} in CSS?
  2. Which one is more efficient and why?
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 03:26

    ul>li selects all li that are a direct child of ul whereas ul li selects all li that are anywhere within (descending as deep as you like) a ul

    For HTML:

    
    

    And CSS:

    li a{ color: green; }
    li>a{ color: red; }
    

    The colour of Something will remain green but or Other will be red

    Part 2, you should write the rule to be appropriate to the situation, I think the speed difference would be incredibly small, and probably overshadowed by the extra characters involved in writing more code, and definitely overshadowed by the time taken by the developer to think about it.

    However, as a rule of thumb, the more specific you are with your rules, the faster the CSS engines can locate the DOM elements you want to apply it to, so I expect li>a is faster than li a as the DOM search can be cut short earlier. It also means that nested anchors are not styled with that rule, is that what you want? <~~ much more pertinent question.

提交回复
热议问题