I made a css-only dropdown menu. The requirement was to have a horizontal bar of items that can each drop down a vertical menu. Furthermore, those items should not drop a tertiary menu, but instead just show bulleted lists. My html has three nested ul
and the menu is working perfectly in all modern browsers. It looks like this:
However, I did not like how the darker box behind the link is starting right of the bullet and does not stretch over the whole menu width, so I played around a bit and finally came to this tweak:
#nav li ul li ul li a {
padding-left:1.8em;
margin-left:-1.8em;
}
Now the bulleted menu item looks just like I wanted:
And due to the nature of em
beeing relative to the font size, it works independently of the font size, like shown with a larger font size here:
I tested this on Internet Explorer 8+9+10(developer preview), Firefox 3+7, latest Chrome, Opera and Safari and it works like a charm.
However, I just dont understand why it is exactly 1.8em that does the job. How come every browser indents the bullet items exactly this far? I searched the internet on this topic, but I did not find anything helpful. Can I be sure this works on future browsers? Are those 1.8em specified in the HTML standard?
Thanks in advance for any hint!
Edit:
To DisgruntledGoat's answer: It would not work if I used 1em/-1em or 20px/-20px. With this style:
#nav li ul li ul li a {
padding-left:20px;
margin-left:-20px;
}
I get this (obviously not scaling with the font size) result for different font sizes:
Similarly, 1em/-1em is also off and looks like on the right in the picture above but scaling with the font size. It still looks like 1.8em is the magic distance for some reason...
Based on many years of inconsistent browsers - I'd say you can't trust them to ever be consistent. The best option is to forcibly control it yourself.
You can use that by simultaneously setting the padding-left and margin-left of an li
. eg:
li {
margin-left: 1.8em;
padding-left: 0;
}
Apparently some (mainly older) browsers use padding and some margin - so be sure to set both.
Given your code, you've set up your ul
such that it has no margin or padding. However, you've set up your li
's such that they have margin-left: 1.8em
:
#nav li ul li ul li {
display: list-item;
margin-left:1.8em;
list-style:disc outside none;
}
#nav li ul li ul li {
margin-left: 1.8em;
padding-left: 0;
}
And there it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With