Setting individual widths for <li> elements using JQuery

My HTML list looks like this:

<ul>
  <li> first element </li>
  <li> second element </li>
  <li> third element </li>
  <li> 4th element </li> 
  ....
</ul>

Using jQuery, I want to set the width of the first <li> to 10% and distribute the remaining width equally among the other <li> elements (e.g., 90% divided by number of elements - 5 in this case).

I need to make sure that the <li> items inside sublists are not affected.

How can I achieve this using jQuery?

Answer №1

If you want to set the width of elements using a function inside the css() method, you can do so efficiently by assigning the width just once.

var li = $('#outermostlist > li');
li.css('width', function(i) {
    return (i === 0)? '10%' : (90 / (li.length - 1)) + '%'; 
})

Here is an example fiddle: http://jsfiddle.net/hzHUn/3/

This code snippet is especially useful when dealing with multiple elements and nested lists, as shown in the Firebug view for 4 elements and 1 nested list.

It's important to note that the calculation 90 / (li.length - 1) could result in the sum of widths exceeding 100%. To avoid this, you can round down the result to the nearest integer using ~~(90 / (li.length - 1))).

Answer №2

Experiment

let $items = $('ul > li');
$items.eq(0).css('width', '10%');
$items.slice(1).css('width', (90 / ($items.length - 1)) + '%');

Answer №3

Here is one way to approach it:

JavaScript

$("#myul li:eq(0)").width("10%").css("background", "yellow");
$("#myul li:gt(0)").width("90%").css("background", "red");

Please note that the background color is just used for better visualization of the outcome.

FIDDLE http://jsfiddle.net/K4pcR/

Answer №4

If you're looking for a solution, consider setting the width of the first li using CSS and the rest using jQuery as shown below:

CSS:

li:first-child{
    width: 10%;
}

jQuery:

$(document).ready(function () {
    var itemWidth = Math.floor(90/($('ul > li').length - 1)); //using Math.floor to ensure it stays within 100%
    $('ul > li:not(:first)').css('width', itemWidth + '%');
});

View Demo Fiddle

EDIT: For browsers like IE <=6 that don't support first:child in CSS, you can use the following jQuery script line to style the first li element.

$('ul > li:first').css('width', '10%');

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

Even after setting [attr.disabled]="false" in Angular, the Textarea still remains disabled

I am currently utilizing ngModel for a textarea, and I would like to be able to enable and disable the textarea based on a certain condition. Even though I have bound it correctly and the value is changing to [attr.disabled]="false", the textarea remains d ...

What is the best way to create a navigation link in PHP along with forms?

If the login credentials are correct, I will be directed to the member page. If not, I should remain on the same page. I am struggling with how to create a link to another page. I have come across some suggestions involving headers, but I am still unsure o ...

Tips for ensuring uniform button height across all cards

I am seeking advice on how to align all the buttons in different cards, despite varying text lengths, to be in the same position at the end of each card. Here is an example of what I am aiming for. Below is my HTML and CSS code: * { margin: 0px; pad ...

AngularJS ng-click incompatibility causing non-functioning popover content

I've gone through all the posts regarding this issue, but unfortunately, none of them proved to be helpful. It seems that the jsfiddle and plunker links provided are no longer functioning as expected. My objective is quite simple - I want to place a ...

Using the <li> element as the primary container for a series of <li>'s within a <ul> is

For my form requirement, I am utilizing Jotforms. After downloading the code, I am currently in the process of customizing the CSS and HTML to fulfill my design needs. Jotforms uses a set of ul , li for managing its HTML structure. However, I encountered ...

Error in linking PHP code to display stored tweets using HTML code

![enter image description here][1]![image of output of twitter_display.php][2] //htmlsearch.html file <!doctype html> <html> <head> <title>Twitter</title> <meta charset="utf-8"> <script> window.onload = function ...

Determining WebElement Clickability in Java and Selenium: Beyond the Basics of isDisplayed, isEnabled, and findElement

There is a common method to test if a WebElement is clickable: It typically involves something like this: public static boolean isElementClickable(WebDriver driver, String accessor){ return driver.findElements(By.xpath(accessor)).size() > 0 & ...

What is the best way to center text vertically in a <div> using CSS?

This is my first attempt at creating a chrome extension, and I am currently working on centering text. Right now, I am using text-align: centre; to align the text horizontally, but I am struggling to figure out how to align it vertically. As a result, my t ...

What is the best way to insert an HTML element without disrupting the layout of the current content?

Consider a scenario where you have a simple webpage with the following content: <h3>Hi!</h3> <img src="http://www.thehindu.com/multimedia/dynamic/01338/IN__GOOGLE__1338298f.jpg"> If you were to add a link like this: <a href="#">m ...

Utilize playing cards as clickable options in Bootstrap 4

I am seeking a creative way to present a boolean selection for users in a card-style format. Despite my efforts, I have not been able to find a suitable solution on StackOverflow. I want to avoid using traditional radio buttons or any generic Bootstrap des ...

What is the process for daily web scraping of news articles using Python?

As I work on developing an application, I require daily news feeds from multiple websites. Utilizing Python's BeautifulSoup library seems like a viable option, but it may not be suitable for websites that display news across various pages which requir ...

Filtering tables in Angular 6 using checkbox options

I have a functional code snippet that filters a table using checkboxes. However, I am facing an issue when unchecking a checkbox. It does not return the original array as expected. .html <ng-container *ngFor="let group of groups"> <label cla ...

Which is better to use: angular.element or $?

Are angular.element and $ essentially the same in AngularJS? Which one is considered best practice and offers better performance? ...

Turn off the perpetual active mode

I have a situation where a link maintains its active state after being dragged and released. This is causing an issue that I need to address. For example, you can see the problem here: http://jsfiddle.net/Ek43k/3/ <a href="javascript:void(0);" id="foo ...

What is the best way for me to send a confirmation response to my API once a user has clicked on the activation link

I have been attempting to send a confirmation message to my API after clicking on the activation link, but despite numerous attempts, I have not been successful. Please see the activation link below: <script type="text/javascript> ...

If a span element does not exist, a bullet can be added within it

Is there a way to add and remove a bullet from an li element with the selected class, only if there is no span already present? Currently, every time the link is clicked, a bullet gets added. What would be the best approach to avoid adding multiple bullets ...

How to enlarge the size of specific letters in HTML

I am looking to enhance the values of C and I. In addition, I am utilizing ::first-text{}. This is currently functioning well. Now, the question arises - how can I elevate the value of I. <p>Creating and Implementing</p> <center> < ...

Is it possible to switch between JavaScript tabs using a button?

I am currently working on a website project where I'm using JavaScript to implement tabs. I want to create a button that can navigate to the next tab. Whether I have to hardcode the tab IDs into the script or not, I just need a way to progress through ...

How can I trigger a function again when an anchor link is clicked and received via Ajax?

I am currently working on creating a unique page transition effect using jQuery and Ajax. This is what I have so far: $(".transitionLink").on("click", function (event) { event.preventDefault(); var href = $(this).attr("href"); window.histor ...

What is the significance of Error: [$injector:unpr] Unknown provider: tProvider <- t <- myActiveLinkDirective?

Just testing how my PROD version of the app looks, ran it through some gulp tasks (minify, strip unused css etc.) and encountered this error: Error: [$injector:unpr] Unknown provider: tProvider <- t <- myActiveLinkDirective Anyone know what's ...