Creating grid columns with evenly distributed widths that match the maximum width of the content within the items

Within a container grid, I have a variable number of child items with different widths.

  1. I am looking to use CSS grid to arrange them so that each column has equal width.
  2. The width of each column should be based on the widest child item.

My initial approach was:

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(max-content, 1fr));
}

However, this code did not produce the desired result:

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(max-content, 1fr));
}
<div class="container">
  <div class="children"> Very long text </div>
  <div class="children"> long text </div>
  <div class="children"> text</div>
  <div class="children"> text</div>
  <div class="children"> text</div>
  <div class="children"> text</div>
</div>

In this scenario, if only 2 columns could fit, the expected layout is as follows:

Very long text | long text     |
text           | text          |
text.          | text          | 

Similarly, if only 3 columns could fit, the expected layout would be:

Very long text | long text     | text         |
text           | text          | text         | 

In both cases, the width of the columns should be based on the max content (i.e., "very long text").

What would be the simplest way to achieve this layout?

Answer №1

In response to your comments about being willing to utilize flex, and if you are also open to incorporating a bit of JavaScript, the following solution should work:

function calculateMaximumWidth()
{
    var container = document.getElementById("_container");
    var maxWidth = Math.max(...[...container.children].map(child=>child.clientWidth));
    container.style.setProperty("--max-width", maxWidth.toString() + "px");
}
calculateMaximumWidth();
.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}
.children {
    border: 1px solid black;
    min-width: var(--max-width);      
}
<div id="_container" class="container">
    <div class="children"> Very lengthy text here </div>
    <div class="children"> long text </div>
    <div class="children"> text</div>
    <div class="children"> text</div>
    <div class="children"> text</div>
    <div class="children"> text</div>
</div>

Depending on your specific framework or rendering method, you may need to implement a ResizeObserver for each cell to update the maximum width, or ensure that it is recalculated after each render.

Answer №2

The issue was brought to my attention in regards to setting max-width: max-content; for the container.

.container {
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 1fr;
  max-width: max-content;
  gap: 10px;
}

.column {
   // any properties
}

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

Creating a React component with a circular loader that displays percentage and texts using Material-UI

I've developed a CircularLoader component using Material UI. The issue I'm facing is that when the variant is set to 'indeterminate', the loader should display without any percentage indication. However, if the variant is 'determin ...

What is the best way to increase the amount of space in a div element using Jquery

I've been working on implementing a sticky menu and highlight menu based on div id in WordPress. The code is complete, but I encountered an issue. When I click on a menu item in the sticky menu, the title goes back to the header where it's not vi ...

Disabling the submit button after submitting the form results in the page failing to load

I am encountering an issue with my HTML form that submits to another page via POST. After the form validates, I attempt to disable or hide the submit button to prevent double submission and inform the user that the next page may take some time to load. He ...

Is there an API available specifically for the HTML Spec, or is there a convenient method for extracting information from the Spec

I'm looking for a simpler way to access information about the HTML specifications through an API or any other easy method. My goal is to create a comprehensive list of all current elements along with their specific attributes. The only approach I am ...

Limiting the click event to the parent div only

I've encountered a problem with my overlay setup. I have an overlay with a child div inside, and I want the overlay to close only when the user clicks on the overlay itself, not the child div. Even though I've implemented the closing function, it ...

JavaScript: Storing text in arrays and managing multiple textareas

Is there a way to load a parent page into an object tag if the code doesn't seem to be appearing in the <object>? Here's what I've tried: var page = parent.document.documentElement.innerHTML; alert(page); document.getEleme ...

Alter the orientation of the current CSS shadow

Looking to modify the direction of a CSS shadow without adjusting the color or strength? box-shadow:green 0 1px 3px; I attempted to change the shadow direction only with the following code: box-shadow:inherit 2px 0 inherit; Unfortunately, this approach ...

When using Javascript's textContent on Node, it fails to retrieve a Unicode character

Issue with retrieving Unicode characters using Javascript textContent on Node I am facing a problem where the textContent method does not return a unicode character stored in a Node. How can I efficiently retrieve unicode characters using textContent or a ...

Changing the CSS attributes of a DIV element while inside a complexly nested IFRAME

Currently, I am dealing with a business intelligence tool that restricts me to working within a deeply nested iframe in order to add code. My goal is to leverage jQuery and/or JavaScript to adjust the left and position CSS of a div located three iframes ab ...

If I choose a different option from the dropdown list, I would like a textbox to appear

Hey there, I have a list of industries and one of the options is "Other". When a user clicks on "Other", a text box should appear for them to specify. I'm struggling to make this work using Django AJAX. Any help would be appreciated! <div class ...

Header Logo not Displaying on _Layout.cshtml in ASP.NET Core

Currently working on a project in Asp Net Core 6 with an application that consists of 2 areas. One issue I encountered is that when logging in with the default user, images display correctly. However, once the address bar changes to localhost:44316/Admin ...

Tips for accessing values from an array in JavaScript

Is there a way to condense the id and name variables into a single variable? I attempted to use $('#vidyagames').tokenInput([variable]); and also tried inputting a URL, but nothing seemed to work. Instead of id and name, I have a function that re ...

Incapable of modifying the text within a div container

I am currently working on a script that translates a Russian forum word by word using TreeWalker. However, there is a specific type of div element that I have been unable to change the text for. That leads to my question: How can I go about changing it? Un ...

Showing a div above another div without relying on z-index

I have designed custom drop down menus that consist of one <div> containing the current value and functioning as a <select> field, with another <div> below it that appears when the top one is clicked, displaying all the <option> val ...

Transfer multiple files by dragging and dropping them into a single file upload option

I was experimenting with adding a drag and drop feature to my website. After trying several scripts, I came across one on CodePen. However, the script allows for the upload of multiple files, while I only need to upload a single PDF or .doc file. Can someo ...

I'm struggling to convert this vertical navigation bar into a horizontal layout using CSS

<nav class="navbar navbar-dark bg-dark sticky-top"> <a class="navbar-brand" href="#">I/H</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> ...

Learn how to implement a split background effect by simply clicking the SPLIT button

let context = canvas.getContext("2d"); // for canvas size var window_width = window.innerWidth; var window_height = window.innerHeight; canvas.width = window_width; canvas.height = window_height; let hit_counter = 0; // object is created using class clas ...

Looking for assistance in merging CSS and HTML codes?

I am working on combining two different codes and could use some assistance. Here is the HTML code: <div class="loader"> <span></span> <span></span> <span></span> </div> Followed by the CSS cod ...

concerning online shopping cart platform

Hello everyone, I am having an issue with my basket. Can someone provide me with the source code to add items to the cart? I have three additional products named Royal, Splroyal, and Postal with values of $22, $45, and $90 respectively stored in radio butt ...

Having difficulty constructing the tree hierarchy in a React project

Trying to implement a tree view in React but struggling with constructing the hierarchical view of information. Reference: https://www.w3schools.com/howto/howto_js_treeview.asp Example on CodeSandbox: https://codesandbox.io/s/unruffled-babbage-9knrz?file ...