ul no margin on first level of nested list?

26,032

Solution 1

Is the first ul a direct descendant of the body? I know you said not adding css classes to the code but I presume adding stuff to a stylesheet is not out the question? If so you could use a style declaration like:

body > ul{
 margin-left:0px;
}

or if you know a div it does sit within:

#your_id > ul{
margin-left:0px;
}

There may also be default padding you need to consider.

Thanks

Solution 2

If you want this to apply to all <ul>s on every page the stylesheet is applied to, this works:

ul {/* Remove margin for all <ul>s (and padding, because different browsers have different default styles) */
     margin-left: 0;
     padding-left: 0;
}

ul ul {/* Add a margin for any <ul> inside another <ul> */
    margin-left: 2em;
}

But if you only want it to apply to certain lists, you need to add something to the HTML to identify those lists (as the other answers have suggested).

Solution 3

You should probably clear the margin of the main <ul>, and then set the margin for a <ul> that's in an <li> element.

ul {
    margin-left: 0px;
}

li > ul {
    margin-left: 10px;
}

Solution 4

Indeed, but a small complementation to TommyBs's answer: you need to apply the id you use in the html list item tag, like so:

<ul>
<li id="your_id">no margin</li>
<li>
    <ul>
    <li>yes margin</li>
    </ul>
</li>
</ul>

And in the css the corresponding line would be

li#your_id {
  margin-left:0px;
}
Share:
26,032
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I want a styled list that doesn't have a margin-left on the first level.. But does on subsequent, leveled sublists.. Anyone know how to do this?

    <ul>
    <li>no margin</li>
    <li>
        <ul>
        <li>yes margin</li>
        </ul>
    </li>
    </ul>
    

    (without adding css classes to the first level of ul or changing any of the code)

  • Admin
    Admin almost 13 years
    Thanks, didn't know about the > css selector!
  • Joe Dargie
    Joe Dargie about 11 years
    @Wesley: note that > doesn’t work in IE 6.