What methods are available in JavaScript for determining the width of a section and implementing proper spacing for a menu?

Is it possible to use Javascript to dynamically adjust the size of each <li> element within the menuArea so that they fill the entire space correctly?

// Could we achieve this with the following code...

var menuSpace = Math.floor((menuAreaWidth - menuButtonsTotalWidth) / (menuButtons.length - 1));
// set positions
var menuButtonsLeft = 0;

$('#menuArea .menuButtonHolder').each(function(i, buttonHolder) {
  if (i < (menuButtons.length - 1)) {
    $(buttonHolder).css({
      'left': menuButtonsLeft + 'px',
      'width': menuButtons[i].buttonWidth + 'px'
    });
  }
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}
#menuArea {
  max-width: 1050px;
  margin: 0px auto;
}
li {
  float: left;
}
li .menuButtonHolder {
  display: inline-block;
}
li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menuArea">
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="news.aspx">News and Events</a></li>
    <li><a href="social.aspx">Social</a></li>    
    <li><a href="blog.aspx">Our Blog</a></li>
    <li><a href="contact.aspx">Contact</a></li>
  <ul>
</div>

Instead of manually adjusting padding values, could we use scripting to handle the resizing of the menu elements to fit the menuArea?

Answer №1

Incorporating Flexbox in your CSS can handle this, avoiding the need for JavaScript.

To achieve this layout, simply include the following lines within your code:

ul {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

If you want all elements to have the same width as the widest element, add this:

li {
    flex: 1;
}

Below is a sample implementation:

ul {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

#menuArea {
    max-width: 1050px;
    margin: 0px auto;
}

li .menuButtonHolder {
    display: inline-block;
}

li {
flex: 1;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}
<div id="menuArea">
<ul>
 <li><a href="/">Home with a really long name.</a></li>
 <li><a href="about.aspx">Home</a></li>
 <li><a href="news.aspx">News</a></li>
 <li><a href="social.aspx">Social</a></li>    
 <li><a href="blog.aspx">Blog</a></li>
 <li><a href="contact.aspx">Contact</a></li>
<ul>
</div>

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

The Hull.js Node.js npm module now offers convex hull computations instead of concave hull calculations

For my project, I am utilizing the node.js module called hull.js to compute a concave hull. However, when following the steps outlined in the "How it works" section on this link, the algorithm seems to halt at the 2nd step, resulting in a convex hull ins ...

challenging multiple substitution within a sentence

My string is as follows: var query = "@id >= 4 OR @id2 < 6 AND @id3 >= 5 AND @name = foo " I want to reverse every "equality" test in this string. This means replacing ' >=' with ' <', ' <' with ' > ...

Using NextJS to render a Link component by creating an element

Struggling to use createElement in NextJS to render a Link, but facing issues. Code: import {createElement} from "react"; import Link from "next/link"; createElement( item.href ? Link : "div", { href: item.hre ...

Is it possible to align the radio-button label above the radio-button in Angular Material 2?

Currently, I am utilizing angular material 2 (material.io) and attempting to position the label of the md-radio-button above the radio button itself. Here's an illustration: View Radio Buttons The official documentation mentions that you can easily ...

Making an element sticky within a container while the parent element is set to overflow hidden

Here is a case where I have generated HTML and CSS code that includes classes for overflow, container height, and sticky positioning: .overflow-hidden { overflow: hidden; } .overflow-x-auto { overflow-x: auto; } .container { max-height: 100px; ...

Switch up the placement of the boxes by moving them in different directions, such as

I've been attempting to recreate the button movement demonstrated in this link , but I'm having trouble achieving it. Using CSS animation, I can make the buttons move in a straight line, here's what I have so far: <div id="box" style=&ap ...

Combining two JSON responses using AngularJS

$scope.addUserJson = $scope.adduser; console.log($scope.addUserJson); Output Object {"username":"Mik911","firstname":"Mike","lastname":"Angel","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563b3f3d16313b373f3a78353 ...

What is the process of using an if statement in jQuery to verify the existence of a property in a JSON file?

I am working on a task to incorporate an if statement that checks for the existence of a specific property in a JSON file. If the property exists, I need to display its value within HTML tags <div class='titleHolder'> and "<div class=&ap ...

The CSS and Javascript files are failing to load

My web page is not displaying my CSS and JavaScript properly when I access it through a folder in the browser. Both files are located within multiple subfolders. I have attempted to rename the files to troubleshoot the issue. <head> <link rel=" ...

Set an attribute without replacing any existing class attributes

I have developed a script that updates the class attribute of the body element on my website when an option is selected from a dropdown menu. However, I am facing an issue where it overrides the existing dark mode attribute. The purpose of this script is ...

Looking to transmit data to your HTML page and incorporate AJAX for your Single Page Application on a NodeJS server with express.js framework?

Is there a way to display the form submitted data on a different HTML page? I am collecting user data on the 1st page (page1.html) and after storing this data in the database, I want to showcase the submitted values on another page, specifically (page4.ht ...

Issues with Navigating through a Scrollable Menu

I'm having a difficult time grasping the concept and implementing a functional scrolling mechanism. Objective: Develop a large image viewer/gallery where users can navigate through images by clicking arrow keys or thumbnails in a menu. The gallery an ...

POST request in Ajax with NodeJs/MongoDB/Mongoose causing an Uncaught TypeError: Illegal invocation

Whenever I attempt to make a POST request using Ajax/Jquery, I keep encountering an error in the console. The specific errors are on lines 67 and 31 in the createTeam.js file: $.ajax({ //line 67 sendInvitation(teamID,_companyName,teamName) //lin ...

Structuring a Javascript project with a focus on component-based architecture

If I am following a component-based architecture and defining each component as an ES6 module, I organize all components in a /components folder. This folder is further divided into subfolders for grouped components. /js /components - header - ...

"Silently update the value of an Rxjs Observable without triggering notifications to subscribers

I'm currently working on updating an observable without alerting the subscribers to the next value change. In my project, I am utilizing Angular Reactive Forms and subscribing to the form control's value changes Observable in the following manner ...

Can you share any recommendations or instances of modifying data within HTML tables using Laravel?

Has anyone ever needed to directly edit and update data in a HTML table using Laravel? I have successfully created "create" tables for different tasks, but I'm interested in being able to modify the data directly on an "index" page. While there are ...

Creating a fixed navigation bar that stays at the top of the page when scrolling

I am trying to create a navigation bar similar to the one seen on W3School's website. I would like the navigation bar to overlap the header when scrolling down, and for the header to appear above the nav bar when scrolling back to the top. Despite m ...

Optimal method for relocating an element efficiently

I'm currently working on a project where I need to implement horizontal movement for a DOM element. The movement should start on mousedown, continue on mousemove, and end on mouseup. This task is especially challenging due to the site's numerous ...

`I am experiencing issues with the HTTP Post functionality`

Whenever I click on the button displayed in the index.html code, an error occurs when the "$http.post" call is made. The web page then displays an alert saying 'Error!', preventing me from saving the new JSON file due to this issue. I need help ...

Discovering an HTML Element in a JavaScript Array with Specific Styling: A Step-by-Step Guide

I am in the process of developing a website that consists of different sections. The concept is simple - by clicking on a button located at the bottom of the page, it will reveal the corresponding div section. For styling purposes, I have initially hidden ...