MAR
MAR

Reputation: 623

Changing parent width by number of its child elements?

In the following example, I have a header with logo-container on the left, menu in the middle and a button on the right. In the example, the menu has 5 top-level items, and 2 sub-menus.

<div class="container">
   <div class="logo_container">
      <img src="logo.png" />
   </div>
   <div id="top-navigation">
      <div id="top-menu-nav">
         <ul id="top-menu">
            <li class="top-item">Top Item 1</li>
            <li class="top-item">Top Item 2
               <ul>
                  <li class="sub-item">Sub-Item 1</li>
                  <li class="sub-item">Sub-Item 2</li>
                  <li class="sub-item">Sub-Item 3</li>
                  <li class="sub-item">Sub-Item 4</li>
               </ul>
            </li>
            <li class="top-item">Top Item 3
               <ul>
                  <li class="sub-item">Sub-Item 5</li>
                  <li class="sub-item">Sub-Item 6</li>
                  <li class="sub-item">Sub-Item 7</li>
                  <li class="sub-item">Sub-Item 8</li>
               </ul>
            </li>
            <li class="top-item">Top Item 4</li>
            <li class="top-item">Top Item 5</li>
         </ul>
      </div>
      <ul id="menu-button">
         <li class="menu-button-cta">Button</li>
      </ul>
   </div>
</div>

As top-level items might be added or removed, I'd like to change the width of the parent element in accordance with the number of top-level items in menu.

For instance:

Is there a way to do it in CSS or jQuery?

Upvotes: 0

Views: 125

Answers (2)

Rachel Nicolas
Rachel Nicolas

Reputation: 1165

Here is my solution with jQuery. First, calculating length of children, then applying style accordingly.

var lengthOfChildren = $("#top-menu").children().length;
switch (lengthOfChildren) {
  case 3:
    $(".container").css("width", "80%");
    break;
  case 4:
    $(".container").css("width", "90%");
    break;
  default:
    $(".container").css("width", "100%");
}

Upvotes: 1

fdomn-m
fdomn-m

Reputation: 28621

You can do this in jquery using .children().length, eg:

$("ul.top-menu").each(function() {
    $(this).addClass(".container-" + $(this).children(".top-item").length);
});

then css:

.container-5 { width: 100%; }
.container-4 { width: 90%; }
.container-5 { width: 80%; }

Upvotes: 2

Related Questions