Remove left padding and margin of First Level of li element of ul

I have this nested Ul li element

Lists can be nested (list inside list)

The first level of li elements Coffee, Tea and Milk taking default Padding and Margin. How to remove the first level of li elements left margin and padding.

<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
      <li>Black tea</li>
      <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

>Solution :

If you have some parent for this first ul element (for example some div), you can use direct child selector >:

div > ul {
  margin: 0;
  padding: 0;
}

but if you have only this structure you posted above, you can use :not selector:

ul:not(li ul) {
  margin: 0;
  padding: 0;
}

you can also reset padding and margin for the first ul element and in the next CSS rule overwrite it for ul nested in ul:

ul {
  margin: 0;
  padding: 0;
}

ul ul {
  margin: revert;
  padding: revert;
}

revert will reset margin and padding to the previous value, but you can also use just some value, like 10px instead of revert

Leave a Reply