How properly I refer to a <li> in the CSS should I use e.g. ul > li or just ul li

I've learned that if I'm refering to a <li> within <ul> or <ol> in CSS i should use ol > li or ul > li but once i forgot put the sign between ol and li and I've found that is working anyway. What is the proper way to do this?

4 answers

  • answered 2017-06-17 19:00 j08691

    They're effectively equivalent since an <li> must be a child of either a <ol> or <ul>.

    The child selector combinator, >, just means that the element on the right side of the rule in x > y must be a child (not just a descendant) of the element on the left. Since with lists this must be the case, your rules are equivalent and either is fine to use. Note that in terms of CSS specificity, that the combinator has no effect.

  • answered 2017-06-17 19:00 Eduardo Sganzerla

    When you use ul li it will take any li inside an ul... That means that if you have, per example this HTML:

    <ul>
      <li>one</li>
      <li>
        <ol>
          <li>one again</li>
        </ol>
      </li>
    </ul>
    

    it will be applied to both li inside the ul and the ol.

    BUT, if you use ul > li it will be applied only to the first li in the example, because it is a direct child of ul.

  • answered 2017-06-17 19:00 lasha maraneli

    Yes it works, because it "Selects all direct child elements specified by “child” of elements specified by “parent”"

    like

    <ul>
    <li></li>
    </ul>
    
    but not
    <ul>
    <li>
       <ol>
          <li></li>
       </ol>
    </li>
    </ul>

    when you use ul > li selector, it will get only one direct child li element on ex.2, if used ul li then you will get tow li elements - all child li elements of ul

  • answered 2017-06-17 19:00 derHugo

    They are not equivalent! Imagine a structure like

    <ul>
      <li id="A"> </li>
      <li id="B">
         <ol>
            <li id="C"> </li>
          </ol>
       </li>
    </ul>
    

    than ul li means ALL <li> in this example A,B and C while ul > li only means the direct childs of the <ul> so A and B but not C