user1930254
user1930254

Reputation: 1321

force width from parent element

I have a main menu #navi. It's items have different width. The submenus should have the same width, as their parents. I made a JsBin to demonstrate it: http://jsbin.com/yusunohage/1

A very very very long submenu should not wider then its parent A longer menu.

Here is the HTML:

  <ul id="navi">
    <li class="menu1">Menu </li>
    <li class="menu2">A longer menu 
      <ul class="children">
        <li>A very very very long submenu</li>
        <li>Submenu</li>
      </ul>
    </li>
    <li class="menu3">Menu item</li>
  </ul>

And the css

ol, ul {
  list-style: none;
  padding: 0;
}
#navi > li {
  padding: 0 10px;
}

li {
  float: left;
}
 ul.children{
   background: gold;


 }

#navi li ul li {
  float:none;
}

Upvotes: 0

Views: 531

Answers (2)

Piotr Dajlido
Piotr Dajlido

Reputation: 2030

PROBLEM:

  • Having the parent element limit the children element without fixing the css width parameter.

SOLUTION

  • Setting the child width to 0px for the purpose of measurement the native parent width.
  • Setting the child width with parent width after measurement.

jQuery:

$('.children li').css('width', 0);
$('.children li').css('width', $('.menu2').width());

Solution here : http://jsfiddle.net/urahara/4m5vkkk2/2/

Upvotes: 2

YourFriend
YourFriend

Reputation: 434

First set the height for parent elements. Then care about the width of child elements.

Just put this in your css code

.menu2{
max-width:140px;
}

Here is the Jsfiddle http://jsfiddle.net/nwL1hku4/

Edited

As you stated above that you don't know about the width of parent element. You may give max-width to child elements, to restrict their width.

Like this http://jsfiddle.net/nwL1hku4/1/

Upvotes: 0

Related Questions