Show equally sized elements using a grid system

I need assistance with displaying fields in a row using CSS grid. I want to display 3 fields in a row with equal width, and if there are only 2 fields, they should also have equal widths. Additionally, if there is only one field, it should take up the full width.

https://i.stack.imgur.com/YdLc4.png

Here's the CSS code I tried:

root: {
        width: '100%',
        display: 'grid',
        gridTemplateColumns: 'repeat(3, 1fr)',
        gridColumnGap: theme.spacing(),
        overflow: 'hidden',
    },

However, this is the result I got:

https://i.stack.imgur.com/1CZNO.png

How can I achieve the expected layout shown in the first image using CSS grid?

Answer №1

There are two innovative solutions to this challenge that can be explored. The first solution involves dividing the grid into 6 columns instead of the traditional 3 columns. By utilizing the nth-child selector, grid items can span across multiple columns with precision. The second solution proposes avoiding the use of grids altogether and opting for a flex-container approach. Within this setup, three flex-containers serve as child nodes, with flex-basis playing a crucial role in achieving the desired layout.

Solution 1: Using a 6 column grid, The key lies in identifying specific grid items and leveraging the span property to extend them across a designated number of columns. For instance, the initial three grid items could be configured to span two columns each using grid-column: span 2;. Below is an example:

.grid-container {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(3, 1fr);
}

.grid-item:nth-child(1),
.grid-item:nth-child(2),
.grid-item:nth-child(3) {
  grid-column: span 2;
}

.grid-item:nth-child(4),
.grid-item:nth-child(5) {
  grid-column: span 3;
}

.grid-item:last-child {
  grid-column: span 6;
}

To view a demo, check out the codesandbox link.

Solution 2:

Given your interest in CSS-grid solutions, I have refrained from presenting the code snippet based on flex-box methodology. However, you might find the codesandbox demonstration showcasing the flex-box solution quite enlightening.

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

In IE8, the :last-child pseudo-class appears to be ineffective

Here is the HTML structure I am working with: <div class="footerMenu"> <ul> <li>Home</li> <li>About</li> <li>Feedback</li> <li>Contact us</li> </ul> ...

Issues with implementing drag functionality in a React and Next image carousel

Attempting to replicate a JS draggable slider in React/Next, but struggling to make it slide with mouse drag. Upon the first click, nothing happens, but when the mouse is released, the slider starts sliding and won't stop unless the page is reloaded. ...

obtaining the value of an input using typescript (put request)

Does anyone know how to extract input values and store them as JSON? I'm having trouble with accessing the input value in this scenario. When I attempt document.querySelector("todo-text").value, it results in an error. const NewTodo: React.FC<NewT ...

The Selenide test encounters difficulties when trying to interact with the Material checkbox

Hello fellow developers. We have incorporated the Selenide framework into our project to create automated UI tests. With our recent switch to Material-UI, we encountered some technical issues with a seemingly simple checkbox. I am currently attempting to ...

Tips for stopping a flex:1 div from expanding to accommodate its abundant content

I'm facing a situation where I need to create two columns, one fixed at 150px and the other filling up the remaining space with scroll functionality for overflow content. Despite trying to use flexbox for this layout, the second column keeps expanding ...

I'm having trouble adjusting the link color in my footer text while navigating Wordpress for the first time

As someone who is new to Wordpress, I am struggling with changing the link color in the footer text. Despite spending hours on it, I just can't seem to figure it out. The files I have been working with are style.css and bootstrap.min.css. I feel lik ...

Input the date manually using the keyboard

I am currently utilizing the rc calendar package available at https://www.npmjs.com/package/rc-calendar When attempting to change the year from 2019 to 2018 by removing the "9," it works as expected. However, when trying to delete the entire date of 1/15/2 ...

The seamless way to eliminate error messages in React using asynchronous methods

A query fetches an array of error messages. One states that "Username is already in use", while the other indicates "Password should be at least 5 characters long". These errors are displayed in React as follows: {this.props.auth.errors ? ( this.prop ...

You cannot call this expression. The type 'String' does not have any call signatures. Error ts(2349)

Here is the User class I am working with: class User { private _email: string; public get email(): string { return this._email; } public set email(value: string) { this._email = value; } ...

Enhance performance with React.memo and seamlessly navigate between routes

Seeking a way to prevent my component from re-rendering on specific paths, I am attempting to achieve this by utilizing React.memo and checking the current path with the withRouter HOC. However, I have encountered an issue where the compare function in Re ...

I am looking to utilize React and Next.js to map my array from an object. The component is a function employing hooks

I am attempting to map an array within an object and encountering some challenges. The structure of the object is as follows: const data = {data: (6) [{…}, {…}, {…}, {…}, {…}, {…}], page: 2, per_page: 6, total: 12, total_pages: 2} I have been ...

Tips for eliminating the page margin in Java when converting HTML using iTextPdf with HTMLConverter

No matter how hard I've tried, setting the body with padding: 0 and margin: 0, as well as attempting to set the doc() with setMargin, nothing seems to be effective ...

What could be the reason for the issue with Material-UI Select element not properly showing the label outline

To showcase a MUI (v5.2.3) Select component along with a label, developers can implement the following code snippet. <FormControl className={classes.formControl} disabled={props.disabled}> <InputLabel id="waiverStatus">Waiver Status ...

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...

Having trouble getting custom select to work with CSS in Firefox?

I want to customize the button (down arrow) located in the right corner of the select box. The HTML code is as follows: <div class="buscaSelect"> <select name="oper"> <option value="value1">Value 1</option> < ...

Masking of the Navigation Button

I designed a responsive navigation bar, but in mobile view, the menu icon is being hidden by the menu headings when displayed. Check out the scenario below with a provided CodePen link. I attempted to adjust padding and float properties without success. An ...

Enhance the look of your MaterialUI React Table with customized Diver Color and Page Dropdown hues. Elevate

I need some assistance with changing the divider color in my TableBody and also the background color of the Rows per page dropdown menu. Any help would be greatly appreciated, thank you! Currently, I am using styled-components ThemeProvider to toggle the ...

The compatibility of MUI Nav Tabs with react-router is limited

Below are the main components: MainComponent.js: import React from 'react'; import { Route, Switch } from 'react-router-dom'; import About from './About'; import Home from './Home'; const MainComponent = () => { ...

The CSS 'top' attribute is without impact

As I begin my journey with CSS, I am eager to grasp some of its behaviors. In the CSS file, the following code is defined: #spa { position : absolute; top : 8px; left : 8px; bottom : 8px; right : 8px; min-height : 500px; min-width : 500px ...

Error 404: Unable to locate protobufjs version 5.0.0

My attempt to incorporate firebase into my project is met with an error: >npm install -S firebase npm ERR! code E404 npm ERR! 404 Not Found: protobufjs@^5.0.0 npm ERR! A complete log of this run can be found in: npm ERR! /Users/my_username/.npm/_l ...