Consider an ordinary 2 levels dropdown menu:
HTML
<ul class="menu">
<li><a href="#">Main item 1</a>
<ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
</li>
...
</ul>
CSS
.nav li { position: relative; float: left; }
.nav li a { display: block; }
.nav li ul { position: absolute; left: 0; top: 39px; }
.nav li ul li { float: left; }
I’d like the second level items to be displayed horizontally, all in one line. It’s not a problem, when we define the width of ul.menu ul. But if the number of the second level menu items varies, we can’t know the width and so the items are displayed vertically.
As vishal and Scott Simpson said,
display: inline-block;is the way to solve the problem. But this method doesn’t work in every browser (at least for now). If a parent hasposition: relative, it indirectly determines the maximum width of its children.So I wrote the following script.