Is it possible to adjust the width of a parent element based on the number of child

In this particular example, I have structured a header with a logo-container positioned on the left side, a menu in the center, and a button on the right. The menu consists of 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>

To adjust the width of the parent element based on the number of top-level items in the menu as they are added or removed, various CSS properties can be utilized. For instance:

  • <ul id="top-menu"> has 5 <li class="top-item"> = .container {width: 100%;}
  • <ul id="top-menu"> has 4 <li class="top-item"> = .container {width: 90%;}
  • <ul id="top-menu"> has 3 <li class="top-item"> = .container {width: 80%;}

If you wish to achieve this dynamic adjustment using either CSS or jQuery, it is definitely achievable through appropriate coding techniques and methods.

Answer №1

To achieve this functionality in jQuery, utilize the .children().length method like so:

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

Follow up with some CSS styling:

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

Answer №2

Here is a jQuery solution I came up with. It calculates the number of children elements first, then adjusts the style accordingly.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customize the List Box Appearance for a Specific HTML Item (Option)

I am working on achieving a specific behavior. When using a listBox (or comboBox), the first element (such as "choose one") should have a unique style. Here is an example of code to test: <style type="text/css"> .testX {font-style: italic;} </ ...

Tips for updating input placeholder text using CSS

Is it possible to change the placeholder text of an input textbox using only CSS? Here's the HTML code snippet: <div class="col"> <input class="form-control" type="text" placeholder="" id="m ...

What can I do to prevent the border from breaking apart when I zoom in?

To address the problem of the 1px black border at the bottom of the header being cut off, try zooming into the page and scrolling right. How can this issue be resolved? ...

Adding border color and width to an ion-avatar element can be achieved by using CSS properties

I've been struggling to add a border color and width to an ion-avatar element in Ionic 4. I've attempted to use various CSS3 code snippets, but nothing seems to work. This is what I have tried: .ion-avatar img{ width: 90px !important; h ...

How to retrieve multiple checked values from checkboxes in Semantic UI React

Trying to enable users to select multiple checkboxes in react using semantic-ui-react. I am new to react. Here is my code: class ListHandOver extends React.Component { state = { data: {} } handleChange = (e, data) => { console.log( ...

Creating a webpage using jQuery and ajax

I am in the process of developing a game using only jQuery and AJAX for navigation and content loading without ever refreshing the page. One issue I am encountering is the need to create functions for every action. For instance: <p onclick="a_function ...

Executing system commands using Groovy is a breeze

One of the scripts I have is a sample.js script that allows me to view files located on the server myHost. It works perfectly: var exec = require('ssh-exec') var v_host = 'myHost' exec('ls -lh', { user: 'username&apo ...

Changing the scroll ball's height using CSS

Can the scrollbar height be adjusted in this section? I've tried using overflow-y:auto, but it seems to start from the header and extend all the way to the bottom. When I scroll, the header moves along with it. Header needs fixing Scrollbar height a ...

The Fusion of JavaScript Frameworks

Is it considered poor practice for a seasoned developer to build a web application using multiple JS frameworks? For instance, when incorporating AngularJS into a project, and certain tasks could be more efficiently achieved with JQuery, should one opt fo ...

What is the best way to implement a user-customizable dynamic URL that incorporates API-generated content in a NextJS and React application?

Seeking assistance with implementing customizable dynamic URLs in Next.js with React. My current project involves a Next.js+React application that uses a custom server.js for routing and handling 'static' dynamic URLs. The goal now is to transiti ...

Angular Material Toolbar Experiencing Color Distortion

To see the issue in action, check out this CodePen: An ongoing problem I've encountered with Angular Material involves distorted colors on the toolbar. The edges of the toolbar display one shade of green, while the middle shows a different shade. Tak ...

Aligning Content in the Header

Currently, I am attempting to place a logo on my WordPress site right at the top of the header above the menus and in the center. Even though I've positioned it at the top, I'm struggling to align it horizontally in the center. I've experime ...

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

Adding input values to a jQuery Ajax POST request

I am currently attempting to send form values to a remote API using AJAX. The necessary information I require from the HTML form element includes the author, string, false, and true. At the moment, I have hard-coded some values but... function sendData ...

Generating a Random Number Within a Specified Range

function generateRandomNumberBetween(start, stop) { var low = Math.ceil(low); var high = Math.floor(high); return Math.floor(Math.random() * (high - low + 1)) + min; } function testRandomNumberGeneration() { var start = parseInt(prompt("Enter low ...

Having issues getting the single div to refresh with `.#div.load(scriptpage.php)` command

I've been attempting to update the content of a specific div (in-game chat) every X seconds or minutes using this simple code. The issue I'm facing is that the content never refreshes or loads the new page. I've searched through various cod ...

Experience the quick sort programming algorithm in action using Vue.js without the hassle of dealing with Promises

I am currently experimenting with the quicksort algorithm visualization using Vue.js for self-educational purposes. However, I am facing some difficulties with async/await implementation. Although array filling and shuffling seem to work fine (although I a ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

Unexpected output from nested loop implementation

Having some arrays, I am now trying to iterate through all tab names and exclude the values present in the exclusion list. json1 ={ "sku Brand": "abc", "strngth": "ALL", "area ...

What's causing this MUI React data grid component to be rendered multiple times?

I have developed a wrapper for the MUI Data Grid Component as portrayed: Selection.tsx: import * as React from 'react'; import { DataGrid, faIR, GridSelectionModel } from '@mui/x-data-grid'; import type {} from '@mui/x-data-grid/t ...