Pieter
Pieter

Reputation: 32755

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.

Upvotes: 3

Views: 3597

Answers (3)

Nick Craver
Nick Craver

Reputation: 630379

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

Upvotes: 3

jackocnr
jackocnr

Reputation: 17416

This is all you need to do (and the spacing should be consistent with your theme):

ul#menu > li > ul {
  position: absolute;
  top: 37px;
}

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382666

If you remove the line-height property from:

ul#menu > li > ul li {
  color:black;
  font-size:10pt;
   /*line-height:30px;*/
  text-align:left;
}

It displays fine or set the line-height to lesser value such as 20px

Upvotes: 0

Related Questions