Prevent block element from overflowing parent element's width

likeitlikeit picture likeitlikeit · May 18, 2013 · Viewed 9.2k times · Source

I have a menu (jsfiddle) which displays like below, it is built from <ul> and <li> elements.

enter image description here

The child menu elements show up below the parent element, and the container is a fixed-width <ul>. The problem I have is that for menu element further to the right, this second-level <ul> overflows the parent element's width, like so:

Current state

How can I make sure that the submenu shows up as in the first picture, but for menu elements further right just moves no further than to the right border, keeping the size intact, instead of overflowing?

enter image description here

Answer

Dory Zidon picture Dory Zidon · May 18, 2013

add to your container overflow-x (you want to keep the y perhaps...) hidden..

#navigation{
    width:900px;
    margin:0px 0 13px;
    padding:0px;
    float:left;
    background:#3b6daa;
    overflow-x:hidden; <------------------------------- note the X..
}

or just make sure your menu isn't fixed width:

#navigation>ul li ul {
    float: left;
    padding: 8px 0;
    position: absolute;
    left:auto; 
    top:42px;
    display: none;
    width:auto;   <------------------- will make it adjust to the contain and the content
    background: #81abdd;
    color: #1c508e;
    list-style: none;
}

or if you want to align it different (like a tooltip that aligns to the right or left of the parent..then I suggest you go down the javascript path..)

Here are some examples:

examples of aligning jquery vertical align 2 divs

jQuery position (also check out width etc) http://api.jquery.com/position/

a great tooltip that aligns all around http://craigsworks.com/projects/qtip/

No out of the box example, but this should give you the right direciton I believe..