Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjusting <ul>'s width to accommodate menu items using jQuery

This is an expansion of a question I posted a while ago: Fitting a <ul>'s width to accommodate the menu items

Is there a snippet of jQuery code that can adjust the width of every <ul> inside a certain <ul> to make sure the <li> items don't overflow? The menu looks something like this:

<ul id="menu">
  <li>
    <a href="javascript:;">Menu 1</a>
    <ul>
      <li><a href="javascript:;">Item 1<a></li>
      <li>
        <a href="javascript:;">Subitem 1</a>
        <ul>
          <li><a href="javascript:;">Subsubitem 1</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

If I don't adjust the <ul> correctly, the layout looks messed up as shown here:

Site menu

You can take a look at the site I'm developing here if you need more information about the CSS or the general structure of the web page.

like image 308
Pieter Avatar asked Apr 21 '26 00:04

Pieter


1 Answers

The width problem actually stems from the width set at the top level here:

ul#menu > li {
  display: block;
  float: left;
  background: url(img/menuitem.png) top left;
  width: 104px;                                 /* here's the issue */
  height: 36px;
  margin-right: 1px;
  text-align: center;
  position: relative;                           /* add this */
}

Since it has a width specified, and its child is in the normal flow, its child is obeying its width, rather than scaling by itself. What you can do is take the child out of the flow, by adding position: realtive; like I have in the above style, then give the child <ul> a position: absolute, like this:

ul#menu > li ul {
  position: absolute;
  top: 36px;              /* top <li> is 36px, go down that much */
}

Then finally, so the anchor text gets a full background, give it a white-space rule like this:

ul#menu > li > a, ul#menu > li > ul a {
  display: block;
  text-decoration: none;
  white-space: nowrap;
}

Here's what the result looks like: alt text

like image 179
Nick Craver Avatar answered Apr 23 '26 14:04

Nick Craver