I don't understand why nobody points to the specific issue and some answers are totally misleading, especially the accepted answer. The issue is that the OP did not pick a rule that could possibly override the margin property that is set by the User Agent (UA) directly on the ul
tag. Let's consider all the rules with a margin property used by the OP.
body {
margin:0px;
...
}
The body element is way up in the DOM and the UA rule matches an element below, so the UA wins. It's the way inheritance works. Inheritance is the means by which, in the absence of any specific declarations from any source applied by the CSS cascade, a property value of an element is obtained from its parent element. Specificity on the parent element is useless, because the UA rule matches directly the element.
#mainNav{
margin:0 auto;
...
}
This is a better attempt, a more specific selector #mainNav
, which matches the mainNav element lower in the DOM, but the same principle applies, because the ul
element is still below this element in the DOM.
#mainNav ul li{
...
margin:0;
...
}
This went too far down in the DOM! Now, the selector matches the li
element, which is below the ul
element.
So, assuming that the UA rule used the selector ul
and not !important
, which is most likely the case, the solution would have been a simple ul { margin: 0; }
, but it would be safer to make it more specific, say #mainNav ul { margin: 0 }
.