Is it possible to adjust the width of an element depending on the number of sibling elements present?

Currently, I am working on designing a grid layout for my application with an uncertain number of columns. My goal is to adjust the width of these columns dynamically based on the number of items rendered in the li elements generated by the Angular code on the client side.

For this project, using any external libraries is not an option.


li {
    display: block;
    float: left;
    width: calc(~'(100% - 30px)/n');
    padding-left: 25px;
    text-align: center;
}

I am wondering if there is a method to automatically count the number of <li> elements within a <ul> container dynamically.

Answer №1

If you're wondering how to dynamically count the <li> elements within a <ul> using JavaScript, you can utilize the .length function along with some JQuery.

$("ul li").length; 
// Alternatively
$("#id_of_ul li").length;

You can then perform any necessary manipulations based on the number of <li> elements returned by the function.

function update() {
  return $("#counter li").length;
}

$(".add").on("click", function() {
  $("#counter").append("<li>Random</li>");
});
$(".count").on("click", function() {
  new_count = update();
  $(".output").html(new_count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="add">Add item</button>
<button class="count">Get count</button>

<br><br>
<div>Number of li tags : <span class="output"> - </span></div>

<ul id="counter">
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
</ul>

Answer №2

This solution provides the same functionality as @Rithwik's answer but without using JQuery.

function update() {
  return document.querySelectorAll("#counter li").length;
}

document.querySelector(".add").onclick = function() {
  document.querySelector("#counter").innerHTML += "<li>Random</li>";
};
document.querySelector(".count").onclick = function() {
  document.querySelector(".output").innerHTML = update();
};
<button class="add">Add item</button>
<button class="count">Get count</button>

<br><br>
<div>Number of li tags : <span class="output"> - </span></div>

<ul id="counter">
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
</ul>

Answer №3

It's baffling to me why my response received a negative rating, so I'll share it again with some code examples for clarification.

Utilizing Flex layout is an incredibly efficient method for ensuring all your columns have equal widths and behave uniformly. Essentially, it functions like a column-oriented grid system (e.g., bootstrap), but with minimal CSS rules.

Below is a snippet of the code:

.parent-container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap; // When wrapped, containers will fit inside the parent. If 'nowrap' is used, they will extend beyond.
    justify-content: space-around;
    align-items: center;
    align-content: center;
}

.children {
    flex: 1 1 auto; // Maintains consistent width for all items
}

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

How to center elements vertically in a navbar using Bootstrap 5

I am currently utilizing bootstrap to design a navbar featuring various links. One of these links is a button, which is causing alignment issues with the rest of the links. body{ background: rgb(27, 25, 25); } .btn{ border-radius: 3em; } ...

What is the best way to retrieve the column name from a specific MySQL table and store it in an

Is there a way to extract column names from a MySQL database? I have been able to retrieve column names using the following code: Array ( [id] => id [BSPKey] => BSPKey [PrintPost] => PrintPost [Barcode] => Barcode [FirstName] => FirstName [ ...

Including code that is tailored specifically for the Internet Explorer browser on Windows Phone devices

While testing the Google Maps API on different browsers and devices, I encountered issues with Windows Phone. It turns out that Google Maps is not supported on Windows Phones, resulting in errors. How can I set it up so that instead of displaying the map ...

Maintain the proportion of the browser window when reducing its size

<html> <head> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <img src="spacer--1200x800.png" width="1200" height="800" /> </body> </html> This section contains CSS ...

Hierarchy Navigation Menu

As someone new to the world of JavaScript and CSS, I have been experimenting with adding a menu from an example on W3Schools. The code is functioning correctly, but now I'm looking to take it a step further by creating a multi-level menu with 2 levels ...

Tips for personalizing the FileField in wtforms to function as an image button

I'm attempting to display an image from my project's directory as an icon instead of the standard "choose file" button. Unfortunately, my attempts thus far have been unsuccessful. Not only is the image not loading, but the original button is only ...

How to customize the background color in a Thymeleaf select element

Here is the HTML code I am working with: <select th:field="*{status.health}" th:value="${status.health}" th:class="health_color" th:name="status_healt ...

Angular encountered an error when trying to access the property "fruits" of an undefined object

When working with Angular, I encountered an issue where I received the error message "cannot read property 'fruits' of undefined." Within my class definition, I have included the following: export class MyClass implements OnInit { fruits: any[] ...

JavaScript tutorial: Creating a function to open multiple nested DIVs

I need help with a website design project where I have content organized in pairs of divs within a grid layout. There are clickable thumbnails that should load different pairs of divs when clicked, but my JavaScript code is only able to turn on one div at ...

Is it possible that CSS files are not being excluded from content scripts in manifest.json?

I am looking to create a chrome extension that enforces a specific CSS style on all websites except for Gmail. However, I am facing an issue where the code in the content scripts section of the manifest.json file is not working as expected. Even though I h ...

Alter the element's class during drag and drop操作

While in the process of dragging an element, I want to dynamically change its class or any CSS property based on its position. Here is what I have achieved so far: https://jsfiddle.net/twfegqgc/ The issue I am facing is that the class changes only when t ...

Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing? Below is the code snippet: HTML <div *ngIf="tempThermometer | async as temp; else loading"> <ng-container *ngIf="temp.length !== 0; else noItems"> &l ...

Using Various Buttons in a Bootstrap Form

I have implemented Bootstrap to create a form. The form structure is as follows: <form action="default_results.php" method="post" class="calculator" name="frmCalculator"> At the beginning of my code, I used the above form code. At the end of the pa ...

HTML/CSS - How to make an element wider than its containing element while staying visible

I am currently working on a web page that generates a table with a green background labeled by an h2 element. The challenge I'm facing is ensuring that the h2 element extends horizontally as far as the user scrolls so that there is always a green bar ...

Background misalignment issue in Internet Explorer 6

My browser is IE6. [UPDATE: You can view the template live at this link: ] I have a template that utilizes 3 <a></a> tags to change the background position and create a button effect. This is how it appears in all browsers https://i.sstatic ...

How to adjust the size of list-style-image in CSS

How can I set custom SVG icons with CSS on a <ul>'s list items? See below: <ul> <li style="list-style-image: url('first.svg')">This is my first item</li> <li style="list-style-image: url('second.svg&a ...

The div has extra white space at the bottom due to the Hide/Show content feature

Having trouble stretching a scrolling div to 100% of its parent container's height? The Hide/Show content feature is causing whitespace at the bottom of the div. Check out the jsfiddle here: http://jsfiddle.net/fkvftff2/1/ LATEST UPDATE: The issue a ...

Tips for adjusting the duration of a background in jQuery

jQuery(document).ready(function(){ jQuery('div').css('background-color','#ffffff').delay(12000).css('background-color','#000000'); }); Hello everyone! I'm having some trouble with this code. I am ...

Are there any CSS hacks available to address the combination of position: sticky and overflow within the parent element?

I've encountered a sticky position issue when the overflow property is set to auto on a parent element. I've tried various solutions like adding an extra wrapper or using clip instead of auto, but none have worked. While I did find a solution usi ...

Troubleshooting a div display issue with jQuery z-index

I've been attempting to adjust the z-Index using jQuery, but I want all DIVs except for one specific one called "importantdiv" to have a z-index ranging from 0 to 100. However, the issue is that importantdiv keeps getting assigned a z-index of 40 inst ...