Ensure the uniform width of columns within the Grid component in React

I am facing an issue with a grid list where the columns have different widths due to varying text lengths. Is there a way to make the column widths equal, ignoring the text length?

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

<Container>
    {elements.map((e, i) => (
        <StyledLabel key={i}>
        <StyledInput
            type="radio"
        />
        <Option>{e.text}</Option>
        </StyledLabel>
    ))}
</Container>
const Option = styled.span`
  display: flex;
  border: 1px solid grey;
  height: 30px;
  font-size: 14px;
  cursor: pointer;
  color: grey;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  overflow: hidden;
  text-transform: uppercase;
  width: 1fr;
`;

const StyledLabel = styled.label`
  cursor: pointer;
`;

const StyledInput = styled.input`
  display: none;
`;

const Container = styled.div`
  width: 300px;
  display: grid;
  grid-gap: 5px;
  grid-template-columns: auto auto;
`;

Answer №1

Instead of relying on auto:

  grid-template-columns: auto auto;

The issue can be resolved by utilizing the fraction unit fr.

A fraction effectively divides the available width by the number of columns, ensuring equal widths for each column regardless of content length.

Here's an example:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.item {
  outline: 1px solid black;
}
<div class="container">
  <div class="item">
    Column one.
  </div>
  <div class="item">
    A second column with more text than the first one. A second column with more text than the first one. A second column with more text than the first one.
  </div>
</div>

Additionally, you have the option to use:

  grid-template-columns: repeat(2, 1fr);

Answer №2

Give this a try:

Instead of using grid, you can also achieve the layout with flex:

.container {
  display: flex;
  border: solid green;
  justify-content: space-between;
}

.item{
  box-sizing: border-box;
  text-align: center;
  padding:5px;
  background-color: red;
  width: 20%;/* adjusted to 20% for gap */
  border: solid;
}
<div class="container">
  <div class="item">AAAAAAAAA</div>
  <div class="item">BBB</div>
  <div class="item">CCCCCCC</div>
  <div class="item">D</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

Tips on triggering ng-click event before the page finishes loading

Is there a way to have the "edit" button appear in a "clicked" state when the page first loads? <div class="buttons" ng-show="!rowform.$visible" style="width: 20%"> <button class="btn btn-primary" ng-click="rowform.$show()">edit</butt ...

Real-time audio feed permanently stuck in Chromium-powered web browsers

Here is how the audio element appears. No interaction seems to take place with it. (Experimented on ungoogled chromium, Edge, and an android device using a default Chrome browser) Below is the HTML code for the audio element: <div> <audio co ...

Enhanced Client Side Validation Leads to Successful Submission and Double Record Addition in Yii

One of the challenges I am facing involves a simple form in Yii that is submitted via AJAX: <?php $form = $this->beginWidget('CActiveForm', array( 'id' => 'application-form', 'enableAjaxValidatio ...

Unlocking the Power of Large Numbers in Angular with Webpack

Error: [$injector:unpr] Unknown provider: BigNumberProvider Recently, I embarked on a new project using Webpack + Angular.JS and encountered an issue while trying to incorporate Bignumber.js. Here's a snippet of my Webpack configuration: resolv ...

How come AJAX is not successfully processing the image file?

It's puzzling that the image file in the form is being processed without any issues when Ajax is not used, but encounters a problem with the Ajax script provided below. I'm struggling to understand why this discrepancy exists... Please note: Th ...

The AJAX POST request encountered an UNKNOWN_PROTOCOL error and did not successfully send the query

I'm encountering an issue while attempting to save a gjson feature in a mongodb using my own server.js file. "use strict"; // Customizable port settings var config = { httpPort: 8080, mongoPort: 27017 } var express = require('expre ...

What are the steps to implement the populate function of Mongoose in Node.js for MongoDB?

I encountered an issue while attempting to retrieve data from the mongo database. Allow me to provide a detailed explanation of what I have done. To begin with, I created two schemas: let CompanySchema = new Schema({ name: {type: String, required: ...

Encountering a bizarre Firefox glitch in React

My React application is encountering a TypeError specifically in the latest version of Firefox. Strangely, it works perfectly fine on Chrome and Safari. The error message I'm getting is: "t.linkNamed(...).fetch(...).then(...).finally is not a functio ...

How to use ng-click to upload images with Multer without a form?

I have successfully implemented multer code to upload a file. However, I am looking to enhance it by using ng-click() to send additional data from my controller via $http post. A simple input field with a button would be ideal. Here is the HTML side: < ...

What are the comparable Java and JavaScript methods for commands used in Selenium?

Today marks my second day delving into the world of selenium. I can't help but wonder if there's a resource out there that lists selenium commands along with their corresponding javascript or java methods. I'm currently working on creating ...

Efficient management of jQuery variables

I am currently working on a form and I have been trying to change an input's type using jQuery. Thanks to the helpful resources available on this website, I learned that I need to clone and replace the input in order to change its type. However, I enc ...

What is the best way to determine if a text matches any of the elements in

Seeking assistance with a demo I am working on. How can I perform a precise comparison between test and the elements in an array arr1? var arr1 = ['noël','noel']; var test = 'noel; if(){ } <script src="https://ajax.google ...

Enhance Website Speed by Storing PHP Array on Server?

Is there a way to optimize the page load time by storing a PHP array on the server instead of parsing it from a CSV file every time the page is reloaded? The CSV file only updates once an hour, so constantly processing 100k+ elements for each user seems un ...

Is there a way to delegate the operation of Object3d.toJSON() to a web worker for optimization?

Is there a way to efficiently convert the active scene in threejs to a JSON object? The process seems to slow down as the models get larger, making it difficult to show a progress bar. I attempted sending the threejs scene to a web worker for conversion, ...

Convert the HTML element from a div to an unordered list (ul) with the help

i am fresh to jquery i would like all divs with these classes turned into unformatted lists : .view-content -----> 'ul' .view-row ----> 'li' .view-organigramme-departements ---> '<ul><li></li></ul&g ...

Is it possible to utilize the Redux state object as the model object for forms?

Looking for guidance in Redux as I am still getting the hang of it. Currently, I have a packageReducer (packageState) that appears as follows: const initialState = { packageList: packageListInitialState, package: {id:'', name: '&apo ...

Q.all failing to execute promises within array

Hey all, I'm currently facing an issue while attempting to migrate users - the promises are not being called. User = mongoose.model 'User' User.find({"hisId" : {$exists : true}}).exec (err, doc)-> if err console.error err ...

What could be causing the Meteor server to take so long to restart and check for dependencies

Currently utilizing Meteor 1.4 along with AdamBrodzinski/meteor-react-boilerplate. After making modifications and saving the code in the editor, I notice a delay of 30-40 seconds before seeing Modified -- restarting in the console. It appears to be check ...

Create a moving background gradient with styled-components

Currently, I am working on setting the background of the <Paper /> component using Material-UI version 1.0.0-beta.25 to display a gradient of colors. The colors are dynamically added by clicking the Add button and selecting one from the color picker. ...

Is it possible to use Facebook Pixel content IDs as MongoDB ObjectIDs?

My NextJs marketplace has a requirement for Facebook Pixel integration. One of the requirements for any Facebook Pixel event is the use of content_ids, which are usually number values in all examples provided. I am curious if it's possible to substitu ...