Determining the Width of a DIV Dynamically with CSS or LESS Depending on the Number of Siblings

One of my challenges involves a parent DIV with a width set to 100%.

Dynamically, this parent DIV is filled with numerous children DIVs.

I am trying to calculate and assign their widths using only the calc method in CSS or LESS. This is because the flex display option doesn't work for me due to working with SVG elements through D3.js.

The desired width formula for each child DIV is: width = (100% / n) - 10

How can I accomplish this task?

In addition, I also need the child DIVs to have alternating colors. I have already figured out how to do this.

Do you have any suggestions on how I can dynamically assign widths using CSS or LESS?

Here is the Jsfiddle link where you can see more details.

Below is the current code I have been working on:

.parent {
    width: 100%;
    height: 50%;
    background: pink;
    border: 1px solid red;
    min-width: 400px;
    min-height: 200px;
}

.child {
    min-height: 200px;
    min-width: 10px;
    border: 1px solid black;   
    display: inline-block;
}

.child:nth-child(even) {
    background: blue; 
    width: calc(100%/n -10);
}

.child:nth-child(odd) {
    background: green;  
    width: calc(100%/n -10);
}

Answer №1

Flexbox is the ideal solution for distributing available space among child elements:

#parent {
  display: flex;
}
.child {
  flex-grow: 1;
  margin: 5px;
}

var parent = document.getElementById('parent');
var child = document.createElement('div');
child.className = 'child';
var numChildren = Math.round(Math.random() * 10);
for (var i = 0; i < numChildren; ++i) {
  parent.appendChild(child.cloneNode(false));
}
#parent {
  display: flex;
  min-width: 400px;
  min-height: 200px;
  background: pink;
  border: 1px solid red;
}
.child {
  min-height: 200px;
  min-width: 10px;
  border: 1px solid black;
  display: inline-block;
  flex-grow: 1;
  margin: 5px;
}
.child:nth-child(even) {
  background: blue; 
}
.child:nth-child(odd) {
  background: green;  
}
<div id="parent"></div>

You can also achieve a similar layout using CSS tables:

#parent {
  display: table;
  table-layout: fixed;
  border-spacing: 10px;
  width: 100%;
}
.child {
  display: table-cell;
}

var parent = document.getElementById('parent');
var child = document.createElement('div');
child.className = 'child';
var numCells = Math.round(Math.random() * 10);
for (var i = 0; i < numCells; ++i) {
  parent.appendChild(child.cloneNode(false));
}
#parent {
  display: table;
  table-layout: fixed;
  border-spacing: 10px;
  width: 100%;
  min-width: 400px;
  height: 200px;
  background: pink;
  border: 1px solid red;
}
.child {
  display: table-cell;
  height: 200px;
  width: 10px;
  border: 1px solid black;
}
.child:nth-child(even) {
  background: blue; 
}
.child:nth-child(odd) {
  background: green;  
}
<div id="parent"></div>

Answer №2

From my understanding, the current CSS method to determine the number of siblings is by using a combination of :nth-child and :nth-last-child, like so:

div:nth-child(1):nth-last-child(3),
div:nth-child(2):nth-last-child(2),
div:nth-child(3):nth-last-child(1) {
   width: 33.3%; /* if there are 3 divs, make them 1/3 of the container width */
}

However, this means you will have to create a selector for each element count you wish to support, with each subsequent selector being longer than the last.

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

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

JavaScript: Working with Nested Callbacks and Retrieving MySQL Data

As I dive into the world of JavaScript server-side code, I find myself grappling with a common issue that many programmers face. In my previous experience with MySQL select queries in PHP, I would simply grab a result and loop through each row, performing ...

Updating the scope value in AngularJS with an asynchronous response is a crucial task for

I am facing an issue with sharing data between AngularJS controllers. The data is obtained through an http request, but when I try to access it in the controller, it returns null. Strangely, if I manually refresh through the UI, the data becomes available. ...

In JavaScript with Node.js, how can one verify a file's size and only download the initial kilobyte of the file?

When using Javascript/Node JS to download a file, you can check the file size and download only the first kilobyte of the file. This is useful if you want to hash the first kb and compare it with the hash of the complete file. If the hashes match and the ...

Tips for extracting and utilizing the values of multiple checked checkboxes in a jQuery datatable

When a button is clicked, I am trying to retrieve the selected values of multiple rows from the datatables. However, with my current code below, I am only able to get the value of the first selected row. function AssignVendor() { var table = $(assig ...

Using the Jquery validation plugin for Internet Explorer 9 when the website first loads

Our website is currently using Jquery v1.9.0 and jquery validation plugin v1.10.0. The form on our site consists of two text boxes and a submit button. When the submit button is clicked, the input elements are validated and a JavaScript function is trigger ...

Using AngularJS to implement modules in a single controller

Currently, I am in the process of learning Angularjs and have two separate template pages - one for login (login.html) and another for the main content (index.html). To incorporate a chart into my index.html page, I am utilizing a directive from here. Th ...

Transition smoothly between sections using fullPage.js with clipping path effects

I am looking to create a unique clipping animation utilizing SVG clipping path. The animation should hide the first section while revealing the second section in a smooth transition using fullPage.js. This idea is somewhat similar to the question discusse ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

Create a class for the grandparent element

Is there a way to dynamically add a class to a dropdown menu item when a specific child element is clicked? Here's the HTML structure I have: <ul id="FirstLevel"> <li><a href="#">FirstLevel</a></li> <li>< ...

Using AJAX and JQuery to automatically refresh a webpage on a scheduled interval

I am attempting to automatically refresh a page every 5 seconds with updated data from an SQL Server. Below is my code snippet: @model Test.Data.Domain.ManufacturingCdMachine @{ ViewBag.Title = "Rimage Details"; ViewBag.JobId = Model.CurrentManufa ...

Adding dynamic HTML to the body in AngularJS based on URL alterations

I am currently developing a single-page application using Angular. I am trying to create a card stack made of divs, similar to this concept. https://i.stack.imgur.com/42M06.png The idea is that the app will have various URL links and a card should be app ...

Loading Collada files with a progress callback function can help track the

Is there a proper way to incorporate a loading bar while using the ColladaLoader? The code indicates that the loader requires three parameters, with one being a progressCallback. progressCallback( { total: length, loaded: request.responseText.length } ); ...

Maximizing AngularJs performance on handheld devices

Recently, I developed an HTML page using material angularjs that functions perfectly on desktops with various browser sizes. However, the issue arises when opening the same page on a mobile device as it behaves like a desktop application instead of adjust ...

What could be causing the TailWind CSS Toggle to malfunction on my local server?

While working on designing a sidebar for a ToDo page using Tailwind CSS, I encountered an issue with implementing a toggle button for switching between dark mode and light mode. In order to achieve this functionality, I borrowed the toggling code snippet f ...

A guide to monitoring and managing errors in the react-admin dataProvider

Rollbar has been successfully integrated into my react-admin app to track uncaught errors. However, I've noticed that errors thrown by the dataProvider are not being sent to Rollbar. It seems like errors from the dataProvider are internally handled w ...

Incorporating a YouTube video

Having trouble integrating a YouTube video that won't play automatically on your website? The video is visible, but just doesn't start playing on its own. What could be causing this issue? Appreciate any help you can provide! ...

How to eliminate a particular item within a string only in rows that include a different specific item using JavaScript

Is my question clear? Here's an example to illustrate: let string = "Test text ab/c test Test t/est ### Test/ Test t/test Test test" I want to remove / only from the line that includes ###, like so: Test text ab/c test Test t/est ### Test T ...

Place elements at the bottom of a webpage on any browser or device with just a single page

I am in the process of creating a website that features a top menu and a background image with text on the home page, covering the full screen. However, I also need to include 3 blocks at the bottom of the screen that should display consistently across all ...

Ways to automatically close browser tab upon successful submission of a form

I have an old file that has been updated. One of the requirements for this file/project modification is to have the current browser window close when the user clicks OK to submit the form. I am curious if this can be done using plain/vanilla JavaScript? ...