Can uniform columns be created in separate HTML elements?

Looking to create a uniform list in HTML, where the columns inside each panel line up perfectly. See the desired layout:

https://i.sstatic.net/FbbPu.png

In this example, Col_1 has a width of "BBBBB", as it is the widest content in that column, while Col_2 has a width of "0x12345678", and so on...

I've searched for CSS solutions but couldn't find any that would work outside the parent container of the elements. Each list item's container acts as a parent to the "grid", making synchronization difficult.

My attempt involved using JavaScript to find the widest element in each column, setting its width to all others, and observing changes with ResizeObserver. However, triggering a resize event every time an item was added to the DOM tree was not ideal.

The JavaScript code I used looked like this:

// Initialize ResizeObserver once
var resizeObserver = new ResizeObserver((entries) => {
    for (var entry of entries) {
        var elem = $(entry.target);
        console.log("Elem resized", elem);
        // Call the resizeColumn() function here
    }
});


// The following code executes every time new data arrives in the listData variable
var listPanel = $("#listPanel");

listData.forEach((entry) => {
    listPanel.append(createListEntry(entry)); // createListEntry() adds a new list item with content
});

requestAnimationFrame(() => {
    listPanel.find("[col-group='Col_1']").each((key, elem) => {
        resizeObserver.observe(elem); // This immediately triggers the callback for some reason
    });
});

resizeColumn("Col_1"); // This should equalize the columns in Col_1 after displaying the list,
                       // But the ResizeObserver call gets triggered multiple times for each item listed

I wish to resolve this without relying on pure HTML/CSS and explore potential JavaScript modifications to prevent triggering the ResizeObserver when showing items.

---------------------------------- EDIT --------------------------------------

The closest working solution involves having the listItem class set to display: contents. Unfortunately, this removes the box styling options like background color or borders due to its nature. Using Firefox-only subgrid would be ideal, but unsupported.

html, body {
  padding: 0.5rem;
  background: #121212;
  color: #ffffff;
  font-family: verdana;
}

.listContainer {
  display: inline-grid;
  grid-template-columns: auto auto auto 1fr;  
}

.listItem {
  display: contents;
  background: #45729a;
  border: 1px solid yellow;
}

.listCell {
  background: #ef4536;
  border-radius: 0.25rem;
  padding: 0.5rem;
  margin: 0.25rem;
}
<div class="listContainer">
  
  <div class="listItem">
    <div class="listCell">AAA</div>
    <div class="listCell">0x00001</div>
    <div class="listCell">aaaaaaaaaaaaaaaaaaaaaaaaaaa</div>
    <div class="listCell">true</div>
  </div>
  
  <div class="listItem">
    <div class="listCell">BBBBB</div>
    <div class="listCell">0x00</div>
    <div class="listCell">bbbbbb</div>
    <div class="listCell">false</div>
  </div>
  
  <div class="listItem">
    <div class="listCell">C</div>
    <div class="listCell">0x12345678</div>
    <div class="listCell">ccc</div>
    <div class="listCell">true</div>
  </div>
  
</div>

Answer №1

One method that could work is to assign the same class name to all elements that should have equal width. Then, use JavaScript to retrieve these elements, compare their widths, and set the largest width as the width for each element.

var widths = [];
document.querySelectorAll('.box').forEach(box => {
    widths.push(box.offsetWidth);
})

Next, implement a simple algorithm to find the maximum value in the widths array and apply this value as the width for all elements.

document.querySelectorAll('.box').forEach(box => {
    box.style.width = 'max_value_here';
})

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

"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter. I initialized a store with a list under state (pages) // state.js const state = { pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}] }; In my ...

Step-by-step guide on triggering a button using another button

I have a unique question that sets it apart from others because I am looking to activate the button, not just fire it. Here is my syntax: $("#second_btn").click(function(){ $('#first_btn').addClass('active'); }) #first_btn ...

Tips for creating a dynamic menu item that stands out with a highlighted style

I would like to add a colored square to highlight the active menu item. .main-menu ul { padding: 0; margin: 0; text-align: center; } .main-menu li { list-style-type: none; display: inline-block; padding: 40px 0; } .main-menu a { font-fam ...

Why won't Firefox display images on my website?

Currently facing an issue with a website I am designing using HTML/CSS (design only). When I open it in Firefox from my hard drive, no images are displayed - instead, there is a small icon indicating that the picture could not be loaded. However, if I righ ...

The issue persists with the $slice function in MongoDb

I am attempting to retrieve records using an aggregate function in MongoDB, but I keep encountering the error message stating that the operator $slice is invalid: db.getCollection('test').aggregate( [ { $match: { 'subjectId': &apos ...

Differences in Print Layout Between Chrome and Firefox when Viewing a PHP Website

I have been working on creating a print command to print a specific div, and I have managed to successfully run the print command using default methods like CTRL + P and also with a button click. The Issue: However, I have encountered a problem where the ...

Blending synchronous and asynchronous testing with Mocha

There is a function that calculates certain values and informs the user about events using callbacks: function returnAndCallback(callback) { callback(5); // not always called return 3; } Incorporating Mocha and Should.js, a test was created: descri ...

Transmit JSON data using Autobahn Python

I am attempting to use sendMessage to send the json content from a URL to a client. def broadcast(self): response = urllib2.urlopen('http://example.com/json?as_text=1') data = json.load(response) for c in self.clients: c.sendMessage( ...

Guide on showing the content of an uploaded file as an object in JavaScript using file reader

When using the file upload function to upload a json file and read its contents, I am encountering an issue where the result is in string format instead of object. How can I display it as an object? Here is my code: .html <div class="form-group"> ...

Verify the presence and delete a table row from the JSON data that is returned

Is there a way to verify the presence of a label in the JSON response and exclude it from the displayed row in my table? In the code snippet below, you can observe that I am returning 'Page Name not defined'. I want to hide this label and any re ...

Is it possible to send an ajax request within another ajax request?

I'm facing an issue with a php file that is sending an ajax request to another file located on a different domain name. The receiving parser then processes the information and sends it via ajax to yet another php file where the final action is carried ...

If a <section> element contains a <header>, must it also include a <footer>?

Here is the current state of my code: <section id="one"> <h2>Section Title</h2> <p>Lorem ipsum...</p> <p>Lorem ipsum...</p> <p>Lorem ipsum...</p> </section> <section id="two"&g ...

Javascript tree structures that enable the drag-and-drop of multiple items

At the moment, our application utilizes the ExtJS tree view. We now have a need for users to be able to select multiple nodes (which the tree view already supports through a pluggable selection model) and then drag these selections to another section of th ...

What is the best way to generate unique mousedown callbacks on the fly?

My goal is to create multiple divs, each with a unique mousedown callback function. However, I want each callback function to behave differently based on the specific div that is clicked. Below is the code I have been using to create the divs and set the ...

Include a carrot icon on a navigation element that is currently active, ensuring it does not disrupt the position of the navigation icon within the container

I am working on a react navigation bar where I want to emphasize each navigation item with a carat when the user is on a specific URL or route. I have been trying to use the :after pseudo-class in Sass to add the carat, but it's not working as expecte ...

tips for passing value to the date field using proctractor

This is the HTML code I am working with: <input id="filter-datepicker" type="daterange" ranges="ranges" class="form-control date-picker" placeholder="Select Date Range" name="sensorDetails.date" ng-model="myDateRange" ranges="ranges" requi ...

The function button.click() is not compatible with Internet Explorer 11 and will not

I have implemented a jqx menu using the code snippet below: <ul style='width: 200px;'> <li onclick="logOffButton.click();">Sign off</li> </ul> My goal is to automatically trigger a click event on the "logOffButton" o ...

Create a table that allows one column to have ample space, while ensuring that the other columns have uniform widths

This HTML/CSS creation features the following: https://i.stack.imgur.com/R8PRB.png However, the challenge lies in making the Very Good, Good, Fair, Poor, Very Poor columns equal in width while still allowing the "question" column to adjust its width acco ...

Is there a way to convert this asynchronous function into a synchronous one so that it returns the value immediately

When it comes to making a Nodejs/Javascript method synchronous, there are several solutions offered by the community. Some suggest using libraries like async and fibrous, but these involve wrapping functions externally. However, I am in search of a soluti ...

Changing background color during drag and drop in Angular 2: A step-by-step guide

A drag and drop container has been created using Angular 2 typescript. The goal is to alter the background color of the drag & drop container while dragging a file into it. Typescript: @HostListener('dragover', ['$event']) public onDr ...