Ensuring grid columns are equal for varying text sizes

I am looking to achieve equal width and spacing for columns without using the width, min-width, max-width properties. Can anyone help me accomplish this using flex or any other method?

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

.d-flex {
    display: flex;
}
.d-flex .col {
    margin: 5px;
    background: #7adaff;
}
<div class="d-flex">
    <div class="col">
        Lorem Ipsum is simply dummy text of the printing and typesetting industry
    </div>
    <div class="col">
        Lorem Ipsum is simply dummy tex
    </div>
    <div class="col">
        Lorem Ipsum
    </div>
    <div class="col">
        Lorem Ipsum
    </div>
    <div class="col">
        Lorem Ipsum is simply dummy text of the printing and typesetting industryLorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
        specimen book. It has survived not only five centuries,
    </div>
</div>

If you have any questions, feel free to leave a comment.

Answer №1

There are a few potential approaches to achieve this layout, one utilizing CSS flex-box design and the other CSS Grid. Both methods avoid setting an explicit width, min-width, or max-width. The flex solution incorporates flex-basis, although it may seem like leveraging a loophole:

.d-flex {
  display: flex;
  gap: 5px;
}

.d-flex .col {
  flex-basis: calc((100% - (4*5px))/5);
  background: #7adaff;
}
<div class="d-flex">
  <div class="col">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry
  </div>
  <div class="col">
    Lorem Ipsum is simply dummy tex
  </div>
  <div class="col">
    Lorem Ipsum
  </div>
  <div class="col">
    Lorem Ipsum
  </div>
  <div class="col">
    Lorem Ipsum is simply dummy text of the printing and typesetting industryLorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
    survived not only five centuries,
  </div>
</div>

Alternatively, a more practical approach is to utilize CSS Grid and take advantage of the fr fractional units:

.d-flex {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 5px;
}

.d-flex .col {
  background: #7adaff;
}
<div class="d-flex">
  <div class="col">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry
  </div>
  <div class="col">
    Lorem Ipsum is simply dummy tex
  </div>
  <div class="col">
    Lorem Ipsum
  </div>
  <div class="col">
    Lorem Ipsum
  </div>
  <div class="col">
    Lorem Ipsum is simply dummy text of the printing and typesetting industryLorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
    survived not only five centuries,
  </div>
</div>

If you need to adjust column counts dynamically, JavaScript may be necessary for this task. The implementation will vary based on specific requirements and could extend beyond the original question scope. Here's a basic example:

// JavaScript utilities:
const D = document,
  create = (tag, props) => Object.assign(D.createElement(tag), props),
  get = (selector, context = D) => context.querySelector(selector),
  sampleText = [
    "Lorem", "ipsum", "dolor", "sit", ... // omitted for brevity 
  ],
  sampleWordCount = sampleText.length,
  addContent = () => {
    let parent = get('.d-flex'),
        text = sampleText.slice(0, Math.floor(Math.random() * sampleWordCount)).join(' '),
        div = create('div', {
          className: 'col',
          textContent: text,
        });
    parent.append(div);
    parent.style.setProperty('--childCount', parent.children.length);
  },
  button = get('button');

button.addEventListener('click', addContent);
.d-flex {
  display: grid;
  grid-template-columns: repeat(var(--childCount), 1fr);
  gap: 5px;
}

.d-flex .col {
  background: #7adaff;
}
<button type="button" id="add">Add content</button>
<div class="d-flex" style="--childCount: 2;">
  <div class="col">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry
  </div>
  <div class="col">
    Lorem Ipsum is simply dummy text
  </div>
</div>

JS Fiddle demo.

References:

Bibliography:

Answer №2

If given the choice, I would opt to define the flex shorthand value individually for each child within the flexbox parent container. By utilizing a custom attribute ([col]) instead of a class (.col), it becomes convenient to adjust column widths as needed (similar to working with grid fractions).

For more detailed information, refer to the CSS code snippet below:

/* Ensure border width is accounted for in total element width */
* { box-sizing: border-box }

/********************/
/* DEFAULT behavior */
/********************/
.d-flex   { display: flex }

[col]     { flex: 1 } /* 1x, all columns equal by default */
[col="2"] { flex: 2 } /* x2, adjust space allocation as necessary */
[col="3"] { flex: 3 } /* x3 */
[col="4"] { flex: 4 } /* x4 */

/*
    'flex' shorthand breakdown: 
        'flex-grow'   - 0 (default, no growth)
        'flex-shrink' - 1
        'flex-basis'  - 0%

    hence 'flex: 1' defaults to 'flex: 1 1 0%'
*/

/*********************************/
/* [OPTIONAL] Responsive Design */
/*********************************/
.d-flex { flex-wrap: wrap } /* default is 'nowrap' */

[col] {
    min-width: min(6rem, 100%); /* Wrap content at specified value */
    /* responsive to viewport width, whichever is smaller */
}

/***************************/
/* DEMO Styling Features */
/***************************/
.d-flex {
    gap: 5px; /* Eliminate the need for margins */
}

.d-flex [col] {
    background: #7adaff;
    padding: 0.5rem; /* Add inner spacing */

    word-break: break-word; /* Break long words if they exceed container */
    -webkit-hyphens: auto;  /* Automatically hyphenate long words */
        -ms-hyphens: auto;  /* Vendor prefixes for optimal support */
            hyphens: auto;
}
<div class="d-flex">
    <div col>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry
    </div>
    <div col>
        Lorem Ipsum is simply dummy tex
    </div>
    <div col>
        Lorem Ipsum
    </div>
    <div col>
        Lorem Ipsum
    </div>
    <div col="2"><b>(demo: with 'flex: 2')</b>
        Lorem Ipsum is simply dummy text of the printing and typesetting industryLorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
        specimen book. It has survived not only five centuries.
    </div>
</div>

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

Looking for a more efficient method to pass components with hooks? Look no further, as I have a solution ready for

I'm having trouble articulating this query without it becoming multiple issues, leading to closure. Here is my approach to passing components with hooks and rendering them based on user input. I've stored the components as objects in an array an ...

Having trouble locating the web element within a div popup while utilizing Node.js and WebdriverIO

I need assistance with a seemingly simple task. I am currently learning webdriverjs and attempted to write a short code to register for an account on the FitBit website at URL: www.fitbit.com/signup. After entering my email and password, a popup appears as ...

Encountering an error in Laravel 5.1 and Vue.js - Error code 21678: Uncaught TypeError: Unable to retrieve 'data' property from null

Recently, while working on my Laravel and Vue.js application, I encountered an issue. Everything was running smoothly until I added another component following the same procedures as before. Suddenly, the data stopped displaying in the table, and I started ...

The customer's status cannot be determined

I've encountered an issue with my TypeScript code that includes a simple if-else logic. endDate: String = ''; customerStatus: String; this.endDate = this.sampleData.customerStartDate; if (this.endDate == null) { this.customerStatus = ' ...

tips for concealing the sorting icon in the DataTables header upon initial load

Is there a way to initially hide the datatable sorting icon upon loading, but have it display automatically when clicking on the header? I've been searching for a solution without success. https://i.sstatic.net/o2Yqa.png ...

"Combining the power of Angularjs and the state

I've been delving into Redux, mainly in the context of using it with React. However, I use AngularJS. Is there a compelling advantage to implementing Redux instead of handling state within AngularJS scope and letting Angular manage the bindings? ...

Repetitive bouncing in a trampoline leads to the error message "Call stack has reached maximum size"

I have been delving into the world of blockchain and experimenting with a simple implementation of "proof of work". Proof of work: export function mineBlock(difficulty: number, block) { const prefix = Array(difficulty + 1).join("0"); function mine(b ...

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...

Tips for aligning a div within a flexbox to the bottom position

I'm having trouble aligning the div at the bottom of the flex box. I attempted to use align-content: flex-end; but it didn't work. Is there a way to keep the <.div class="parameters"> at the bottom of the row? Especially when the ...

Transforming Nested JSON Data into an Interactive HTML Table

I am attempting to transform this nested JSON data into an HTML table: { "language":"en", "retrieved_url":"https://www.canlii.org/en/ca/scc/doc/1986/1986canlii46/1986canlii46.html?autocompleteStr=r%20v%20oakes&aut ...

How to iterate through a Vue data object using forEach loop

I am currently working with a variable in my data: data: function () { return { myVariable: false, } } I'm trying to figure out how to access this variable within a looping function, like the example below: anArray.forEach(functi ...

Having difficulty including the Column Name in the Jqgrid footer for sum calculation

I was working on the Jqgrid code and found a way to display the sum correctly in the footer of the grid. var colSum = $("#dataGrid").jqGrid('getCol', 'Amount', false, 'sum'); $("#dataGrid").jqGrid('footerData', &a ...

restructure the HTML based on a jQuery condition

Using jQuery to Refresh HTML Content function(data) { if(data === "importtrue") { $('#rebuildme').//function like .html } else { $('#rebu ...

Change all instances of the subtraction symbol to parentheses using jQuery

--html-- <table> <tr> <th>a</th> <th>b<th> </tr> <tbody class = "tabledata"> <tr>a</tr> <tr>b</tr> </tbody> </table> --jquery-- $('.tabledata').empty(); for ( ...

Automatically adjusting the height of a Bootstrap carousel as the token-input list grows in size

I am working on a carousel that functions as a form. One of the carousel items contains a multi-select box. How can I automatically increase the height of only that specific carousel item as the height of the multi-select box increases? The first image sh ...

What is the method to set precise values on a range slider?

Currently, I am developing a PHP website that requires a slider for displaying the years of publications. In essence, I need the slider to navigate through the different years when the publications were released. // Database connection and other PHP code ...

Function utilizing variables parsed by Angular directive

I am currently working on a directive that I have created: feedBackModule.directive("responseCollection", ['deviceDetector', function (deviceDetector) { return { restrict: "E", templateUrl: 'js/modules/Feedback/direc ...

Personalizing the form controls in Bootstrap for selection options

Utilizing Bootstrap's form-control class helps maintain a consistent style for both form input and select option elements. However, when using form-control on select elements, it results in an unsightly drop-down button appearance in Firefox.https://i ...

What is the typical number of open CLI terminals for a regular workflow?

After experimenting with Gulp, Bower, ExpressJS, and Jade, I have settled on a workflow that I am eager to switch to. The only issue I am facing is the need to have two terminals open simultaneously in order to use this workflow efficiently. One terminal ...

Adding an HTML tag to a div using jQuery

Currently, I am trying to dynamically add a field to my form using the following code: Using JQuery: $('#addField').click(function(){ $('#divTest').append("<html:text property='titles'/> <br> <br>"); }) ...