-1

ul > li (selector) doesn't work. What am I missing here?

/* Part 1 */
ul > li{
  margin-top:30px;
}

/* Part 2 */
/* ul .test{
  margin-top:30px;
} */
<ul>
<li class="test">item1</li>
<ul>
  <li>subitem1</li>
  <li>subitem2</li>
</ul>
<li class="test">item2</li>
<li class="test">item3</li>
</ul>

https://jsfiddle.net/gy5r3noh/
Shouldn't Part 1 and Part 2 in css be equal? But It isn't. ul > li should select all li children of ul (like class=test I created), but it doesn't work by ul > li.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
Reza Mas
  • 13
  • 3

3 Answers3

1

Ignoring the fact that your HTML is invalid as j08691 has pointed out, and assuming your inner ul is intended to be wrapped in a li element:

  1. ul > li selects any li element which is a child of any ul element.
  2. ul .test selects any element with a class of "test" contained within any ul element.

One and two give different results with your HTML structure because your nested ul does not contain li elements with a class of "test". Example one applies to both the outer and inner ul elements, whereas example two only affects the li elements with a class of "test" (which there are none of within your nested ul).

Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
0

you HTML is invalid, ul can't have ul as direct child

ul > .test {
  margin-top: 30px
}
<ul>
  <li class="test">item1
    <ul>
      <li>subitem1</li>
      <li>subitem2</li>
    </ul>
  </li>

  <li class="test">item2</li>
  <li class="test">item3</li>
</ul>
dippas
  • 58,591
  • 15
  • 114
  • 126
0

/* Part 1 */
ul > li{
  margin-top:30px;
}

/* Part 2 */
/* ul .test{
  margin-top:30px;
} */
<ul>
<li class="test">item1</li>
<ul>
  <li>subitem1</li>
  <li>subitem2</li>
</ul>
<li class="test">item2</li>
<li class="test">item3</li>
</ul>

Here, Html Should be like,

<ul>
<li class="test">item1
  <ul>
    <li>subitem1</li>
    <li>subitem2</li>
   </ul>
</li>
<li class="test">item2</li>
<li class="test">item3</li>
</ul>
  • How is this different from this answer: http://stackoverflow.com/a/43663028/578411 – rene May 06 '17 at 09:12
  • Its same, Nothing different. I just created Html structure, – Fatema Taher Kapasi May 06 '17 at 09:17
  • There is no point in having answers that don't add anything new. We want (new) answers to add value, not repeat what is already there. – rene May 06 '17 at 09:20
  • Yes, I know and I try to educate you a bit how you can improve. Being open for advice is a good starting point ;) Enjoy your stay on Stack Overflow. If you need a bit extra guidance remember we have an [help] – rene May 06 '17 at 09:23