A guide to automatically wrapping CSS grid columns onto the next row in React's Material-UI

I'm working with a CSS grid that contains a varying number of elements. Here's an example:

 <Box className={classes.Grid}>
                <Button variant="outlined">1</Button>
                <Button variant="outlined">2</Button>
                <Button variant="outlined">3</Button>
                <Button variant="outlined">4</Button>
                <Button variant="outlined">5</Button>
                <Button variant="outlined">6</Button>
                <Button variant="outlined">7</Button>
                <Button variant="outlined">8</Button>
                <Button variant="outlined">9</Button>
                <Button variant="outlined">10</Button>
</Box>

In addition,

const useStyles = makeStyles({
    Grid: {
        display: "grid",
        gridTemplateColumns: "repeat(3, 1fr)",
        gridGap: "10px",
        margin: "auto",
        width: "90vw",
    }
});

My question is how can I adjust the number of columns in each row based on the size of the grid element? It's worth noting that each child element has specific dimensions (220px by 200px).

Answer №1

If you're looking to fill the available space with rows, then you should check out @robske_110's solution.
However, if you prefer more flexibility in determining the size and layout, I suggest utilizing the breakpoints feature within MUI. You can find a working example at this sandbox link, along with the code snippet below.

const useStyles = makeStyles((theme) =>
  createStyles({
    Grid: {
      display: "grid",
      gridTemplateColumns: "repeat(3, 1fr)",
      gridGap: "10px",
      margin: "auto",
      width: "90vw",
      [theme.breakpoints.down("sm")]: {
        gridTemplateColumns: "repeat(2, 1fr)"
      }
    }
  })
);

Answer №2

If you're in search of an auto-fill feature that populates rows with elements to fit the available space, try this snippet:

gridTemplateColumns: "repeat(auto-fill, 5em)"

Feel free to adjust the '5em' value to suit your requirements.

To ensure a minimum size for buttons while allowing them to expand and fill the width dynamically, consider combining it with minmax():

gridTemplateColumens: "repeat(auto-fill, minmax(5em, 1fr))"

You can modify the '5em' accordingly based on your button sizes.

For a visual representation in plain HTML, check out this example:

.grid{
  display: grid;
  gap: 1em;
  grid-template-columns: repeat(auto-fill, minmax(10em, 1fr));
}

.grid > div{
  width: 100%;
  text-align: center;
  background: grey;
}
<div class="grid">
<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
<div>Element 4</div>
<div>Element 5</div>
<div>Element 6</div>
<div>Element 7</div>
<div>Element 8</div>
<div>Element 9</div>
</div>

For more details, visit: https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns

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

Adding a translucent overlay on top of a background image within a div, while keeping the text on top

Here is the current code that I am working with: <div class="square"> <div id="wrapper"> <h2>Text</h2> <h3>Text</h3> </div> </div> .square { padding: 10px; width: 150px; height ...

What is the reason behind the functionality of inline-block?

As a beginner in html and css, I am facing an issue with displaying two h3 elements on the same line. I have tried using display:inline-block, but it's not working as expected. You can check out an example on jsfiddle here. I have provided 4 different ...

How come Express GET requests always provide HTML as the response content type?

I'm facing an issue where my API GET routes always return HTML instead of JSON data. Here's an example of the code causing the problem: router.get("/allposts", auth, async (req, res) => { try { const Posts = await Post.fi ...

Displaying a div when a radio button is clicked in React

I am attempting to create a functionality where clicking on one radio button will display another div in React. As a beginner in React, I have tried implementing the code below but encountered issues with hiding and displaying the content based on user inp ...

Strategies for selecting elements in jQuery that are displayed and not hidden

Here is the structure of my HTML code : {# Navigation for xs screens #} <div class="small-screen-nav hidden-lg hidden-md hidden-sm col-xs-12" style="padding: 0;"> <ol class="breadcrumb" style="padding: 0px 7.5px"> <li><a h ...

Trying to resolve w3 validator error and warning issues

While checking my HTML code using the W3 validator, I encountered an error and warning message: Line 21, Column 23: The ID menuItem was first used here. <li id="menuItem"><a href="#visit">Ten Places to Visit</a></li> ✉ Line 29 ...

Managing an extensive JSON file

With plans to create a project showcasing "UFO" sightings, I initially aimed to find an API for this but came up empty-handed. However, I stumbled upon a substantial 33mb JSON file containing reports of UFO sightings with over a million lines of code. Now, ...

Troubleshooting the issue of locating React static files within a Python environment

In my project, the back end is built with Python and I have utilized ReactJS for the front end development. Even though the project runs successfully when using the python manage.py runserver command, there seems to be an issue with locating the static fil ...

The toggle feature in jQuery doesn't hide content in the same manner as it was originally shown

Just diving into the world of jquery and I'm experimenting with the toggle function to display and hide a div, along with adding or removing an active class. http://jsfiddle.net/MAkyw/ I've encountered 2 issues: 1) The 'active' class ...

What is the most efficient way to store the context values in local storage?

My goal is to save any changes made to the contact list in the local storage when a contact is added or removed. However, I encountered an error with the code I wrote for local storage. How can I rectify this issue? The error message "State.contacts is ite ...

Choosing premier class and modifying characteristics

Looking for a solution to hide a div without modifying the HTML code directly? By using JQuery, you can manipulate the appearance of elements on a page. While it's possible to select the first instance of a class and retrieve its value, adding an attr ...

What is the method for populating a dropdown using ajax in the Jade template engine?

Looking to dynamically populate a dropdown based on the selection of another dropdown. Here's the code snippet: script. var b_name = []; function jsFunction() { var client = document.getElementById('drop_client'); var c_name = cli ...

Parsing error occurred due to an unexpected token during variable substitution, the expected token was "..."

My dynamic code for adjusting a text field is functioning well. The current version of the code works fine: if (props.responsetxt === null) { txtField = ( <TextField autoFocus margin="dense" id="name" label= ...

Purging data when no input is detected in React.js

I need to figure out a reliable way to detect when my input field has been cleared so that I can clear the associated data. Currently, I am using the logic if (searchTerm.length === 0) to check for a cleared input. However, I have also experimented with i ...

Popover disappears when scrolling the page, but its position remains constant in Angular 4+

After clicking on an icon, a popover appears. I've noticed that the popover has a delay set, but when I scroll, the popover also moves along with it. Is there a way to keep the popover in place and not have it affected by scrolling? <md-badge cla ...

Passing arguments from the command line to an npm script

The scripts section in my package.json is currently set up as follows: "scripts": { "start": "node ./script.js server" } This allows me to use npm start command to initiate the server. All working well so far. However, I ...

Can you explain the distinction between using destructuring syntax and an empty parameter when calling a render function?

After writing some code in React, I found using this.props to be too verbose. So, I researched some articles and learned how to approach this issue while coding. class MyComponent extends Component { // the traditional method render() { re ...

What could be causing the overlap of my input box with its parent container?

Here is the code snippet I am working with: <section className="createTodo-box"> // parent <div className="createTodo-inside"> // child <Input value={this.state.text} style={{ width: '200px' }} ...

Broadcasting with Socket.emit may not reach all connected clients

As a newcomer to using react with socket.io, I find myself stuck on the issue of retrieving data permanently on the frontend. My goal is to create a small game where multiple users can join starting from a lobby page. The challenge arises when I attempt t ...

The specified 'Object' type does not match the required 'Document' constraint

I need assistance with running a MERN application to check for any issues, but I keep encountering this error across multiple files. Error: The 'CatalogType' type does not meet the requirements of 'Document'. The 'CatalogType&apo ...