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?

.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

The canvas game's animation can only be activated one time

I am currently working on designing a straightforward canvas game: Here is the code snippet located on CodePen var canvas; var ctx; var x = 300; var y = 400; var r = 0; var mx = 0; var my = 0; var WIDTH = 600; var HEIGHT = 400; function circle(x,y,r) ...

Always ensure that only one div is visible at a time

I am currently working on a project where I cannot use ng-cloak due to the way the css files are loaded. I have been exploring alternative solutions and have tried a few different approaches. My main goal is to ensure that two icons are never shown at the ...

Minifying Angular using grunt leads to 'Error initializing module' issue

Currently, I have multiple controllers, models, and services set up as individual files for preparation before minification. My goal is to combine and minify all these files into one JS file for production. To illustrate how my files are structured, here ...

Ways to incorporate color gradients into the corners of CSS cards

Below is an example of a basic bootstrap card: Example 1: https://i.stack.imgur.com/DK2Sz.png I attempted to draw blue and green colors side by side, but was only successful in drawing blue as shown below: Example 2: https://i.stack.imgur.com/CcSzP.png ...

What is the best way to incorporate CSS from node_modules into Vite for production?

I have a TypeScript web application where I need to include CSS files from NPM dependencies in index.html. Here is an example of how it is done: <link rel="stylesheet" type="text/css" href="./node_modules/notyf/notyf.min.css&quo ...

Element on webpage "Expands" When Scrolled into Visibility

After posting a question on Stack Overflow, I noticed discrepancies between the element dimensions reported by Chrome Inspector and Selenium WebDriver. While Chrome Inspector showed w = 979, h = 1961, Selenium returned dimensions of 979 and 1461 respective ...

Facebook and the act of liking go hand in hand, growing together

I am working on a website where I want to include Facebook like and share buttons with counters. To achieve this, I used Facebook's own links to generate these buttons for the specific URL. The issue I encountered is that when I like or share the page ...

Utilize the <wbr> tag within FormattedMessage and assign it as a value while coding with TypeScript

Trying out the optional word break tag <wbr> in a message within <FormattedMessage id="some:message" />. Context Some words or texts are too lengthy for certain parent elements on smaller mobile screens, and we have a column layout t ...

AngularJS - Utilizing Google's Place Autocomplete API Key

Recently, I started digging into Google's APIs and attempting to integrate the Places Autocomplete API with Angular. Although I'm fairly new to autocomplete features in general, I haven't included the jQuery library in my project yet. I&apos ...

using database URL as an AJAX parameter

I am currently working on a Python CherryPy controller that needs to validate a database URL by attempting a connection. However, I am facing challenges with passing the parameter to the method. Below is my AJAX call: $.ajax({ async: false, ty ...

Navigating through sibling elements can be accomplished by using various methods in

Can someone help me figure out how to assign unique IDs to 6 different Div elements as I step through them? The code snippet below is not working as expected, giving all Divs the same ID. What is the correct way to accomplish this task? $('#main-slid ...

What are some ways to enhance Redux's performance when handling rapid updates in the user interface?

I have been facing a challenge with integrating a D3 force graph with my redux state. During each 'tick' update, an action is dispatched to update a collection of positions in the redux state. These positions are then combined with node data to u ...

Can a YouTube video be triggered to play when a specific CSS style is selected?

I am searching for a method to display and play different YouTube videos based on a selected CSS style from a drop-down menu. I believe JavaScript can be utilized to detect the chosen CSS. Include the following in the html header of the page. <script ...

Using identical CSS for two separate layouts

Imagine having to work with an html page that cannot be altered in any way. The only tool at your disposal is CSS. The page is loaded and shown through an iframe from a different domain. This particular page serves as a payment gateway, displaying either ...

Creating a dynamic design with a responsive background image and three columns of engaging content placed on top using Bootstrap

I'm struggling to translate a design mockup into Bootstrap 3.3.6 Here is an image showcasing the concept I am aiming for: The blue background represents an image, with grey text boxes overlaid on top (one of which includes a form). The entire layout ...

Exploring the location where an XMLHttpRequest/Ajax link is executed

I am relatively new to the world of Ajax/XMLHttpRequest and I am currently trying to wrap my head around its functionality. My current project involves developing an inventory program that essentially allows users to add tools to a digital box. On the mai ...

picture protrudes from the frame [WordPress template]

Check out my website: If you scroll to the bottom of the site, you'll see an image of a bride sitting on a couch. I recently added this code to the stylesheet: .novia img {min-width:1000px; float:none;} This code was meant to maintain a fixed heigh ...

Obtain a collection of the corresponding keys for a given value from dictionaries

I'm implementing a function that retrieves a list of keys associated with a specific value in the dictionary. Although I am able to print out the first key successfully, I'm facing difficulties in displaying subsequent keys. I understand that I ...

The parameter value experiences an abrupt and immediate transformation

I recently created an electron app using Node.js and encountered a peculiar issue that I am unable to resolve: Below is the object that I passed as input: { lessons: [ name: "math", scores: [90, 96, 76], isEmpty: false ] } ...

Why does my script seem to be missing from this GET request?

Encountering an issue while setting up a page using npm and grunt. Request URL:http://localhost:9997/bower_components/requirejs/require.js Request Method:GET Status Code:404 Not Found The problematic html code is as follows: <script> ...