Reputation: 4691
My webpage has a list and I want the list to start just a few pixels down. The problem is, when I set margin: 0 0 0 0;
it naturally does nothing, but setting margin: 1px 0 0 0 ;
causes it to 'jump' down many pixels.
<nav>
<ul>
<li>Layer This</li>
<li>And that</li>
<li>Ooooh</li>
</ul>
</nav>
CSS
nav {
background:#f0364f;
}
nav ul {
padding:1px 0 0 0; /* THIS IS THE FAULT. */
}
nav ul li {
list-style:none;
margin:20px 0;
background:#B8C5CD;
padding:5px;
}
So, in the CSS, if you change from
nav ul {
padding:1px 0 0 0; /* THIS IS THE FAULT. */
}
to
nav ul {
padding:0 0 0 0; /* THIS IS RENDERING CORRECTLY BUT, I WANT A PADDING! */
}
You will see the issue. When the padding is set to 0 it works as expected. Why does adding 1 pixel make it jump so far down?
EDIT Please note, although a fix is nice, I'm more interested in why this behaviour occurs (I'm sure I can find a hack easily enough, but I could not find any information into understanding the cause)
Upvotes: 2
Views: 198
Reputation: 679
Rather than using :first-child
, I would prefer doing something as mentioned below because :first-child
may have cross browser compatibility issues.
<nav>
<ul>
<li class="first">Layer This</li>
<li>And that</li>
<li>Ooooh</li>
</ul>
</nav>
nav ul li.first{
margin-top:0;
}
The solution is basically same but targeting element based on class rather than :first-child
may just help you prevent some cross browser issues.
Hope this helps :)
Upvotes: 1
Reputation: 269
Try giving padding to first child instead of ul
nav ul li.test {
padding-top:1px;
}
nav ul {
padding:0 0 0 0;
}
<nav>
<ul>
<li class="test">Layer This</li>
<li>And that</li>
<li>Ooooh</li>
</ul>
</nav>
Upvotes: 0
Reputation: 6253
You set margin
for your li
(child element). When you set padding
for ul
(parent element), you passed margin collapsing.
Set margin
for second li
element and next:
nav ul li + li {
margin-top: 20px;
}
Upvotes: 2
Reputation: 36784
This is because when you have no padding on your <ul>
the margin for your top list item collapses. When it has padding, the margin is acknowledged.
I'm assuming from your question that you don't want any margin before the first list item, you can remove any margin from the first item easily:
nav ul li:first-child{
margin-top:0;
}
Upvotes: 2