Troubleshooting problem with aligning grid items at the center in React using

I've been facing a challenge in centering my elements group using the material ui grid system.

Problem: There seems to be excess margin space on the extreme right.

Code snippet:

const renderProjects = projects.map(project => (
    <Grid item xs={12} sm={6} m={3} lg={3} key={project.title}>
      <ProjectCard
        title={project.title}
        description={project.description}
        image={project.image}
      />
    </Grid>
  ));

  return (
    <Grid
      container
      direction="row"
      justify="center" <==== Seems to not work as expected
      alignItems="center"
    >
      { renderProjects}
    </Grid>
  )

The ProjectCard component has the following style:

const useStyles = makeStyles({
  root: {
    maxWidth: 300,
  },
  media: {
    height: 100
  },
});

Screenshot of the grid layout:

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

I'm primarily a backend developer working on client projects, and I haven't been able to find a resolution for this. Any help would be greatly appreciated. Thank you!

Answer №1

After encountering a similar problem, I found that using justifyContent instead of justify resolved the issue without requiring a separate style tag.

(Version MUI v5.8.0)

Answer №2

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

It is essential to add some margin to your cards for better layout spacing. Currently, the flex items are occupying X % of space based on the screen size (defined by your xs, sm, m, & lg props), and the cards have a maximum width set at 300, resulting in the noticeable "space to the right" indicated by the orange section in the provided image.

const useStyles = makeStyles({
  root: {
    maxWidth: 300,
    margin: "auto", // <-- include this
    marginBottom: "10px" // <-- only a recommendation; you may choose to add more spacing below each card
  },
  media: {
    height: 100
  },
});

const projects = [{
  title: "sample title",
  description: "desc",
  image: "https://via.placeholder.com/300x100"
},{
  title: "sample title",
  description: "desc",
  image: "https://via.placeholder.com/300x100"
},{
  title: "sample title",
  description: "desc",
  image: "https://via.placeholder.com/300x100"
},{
  title: "sample title",
  description: "desc",
  image: "https://via.placeholder.com/300x100"
},]

const useStyles = makeStyles({
  root: {
    maxWidth: 300,
    margin: "auto",
    marginBottom: "10px"
  },
  media: {
    height: 100
  },
});

function App() {

  const renderProjects = projects.map((project, index) => (
    <Grid item xs={12} sm={6} m={3} lg={3} key={index}>
      <ProjectCard
        title={project.title}
        description={project.description}
        image={project.image}
      />
    </Grid>
  ));

  return (
    <Grid
      container
      direction="row"
      justify="center"
      alignItems="center"
    >
      {renderProjects}
    </Grid>
  )
}

function ProjectCard({title, description, image}){

  const classes = useStyles();

  return(
    <Card classes={{root: classes.root}}>
      <CardActionArea>
        <CardMedia
          classes={{media: classes.media}}
          component="img"
          image={image}
          title={title}
        />
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2">
            {title}
          </Typography>
          <Typography variant="body2" color="textSecondary" component="p">
            {description}
          </Typography>
        </CardContent>
      </CardActionArea>
      <CardActions>
        <Button size="small" color="primary">
          Share
        </Button>
        <Button size="small" color="primary">
          Learn More
        </Button>
      </CardActions>
    </Card>
  );
}


ReactDOM.render(<App/>, document.getElementById("root"));
<body>
  <div id="root"></div>

  <!-- React -->
  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

  <!-- Babel -->
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

  <!-- MUI -->
  <script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>

  <script type="text/babel">
    const { Button, Grid, Card, CardActionArea, CardMedia, CardContent, Typography, CardActions, makeStyles } = MaterialUI;
  </script>
</body>

Answer №3

Try using the correct md property instead of m when working with the Grid item to see if that solves the issue.

Answer №4

To create a grid layout with evenly spaced items, simply include the following code within the main container:

style={{display:'flex'; justifyContent:'space-evenly'}}
.

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

React hook call is not valid

https://reactjs.org/docs/hooks-custom.html Creating custom Hooks allows you to abstract component logic into reusable functions. This is exactly what I aim to achieve: abstract my component logic into reusable functions for other components. Here is an ex ...

Contrasting code splitting and lazy loading techniques in React

I could use some clarification on the term load in this context - does it refer to loading into memory directly or fetching over the network before loading into memory? ...

I'm looking to optimize my paragraph for small screens by incorporating a Google AdSense banner

I need help adjusting my content with a Google banner for small screens. Here is an example image: Example Image Within the parent div with the class name parent-content, there is a banner div named ad3. Below is the code I have written for screens with ...

What is the best way to center a CSS arrow vertically within a table cell?

I'm having trouble with aligning a CSS arrow next to some text inside a table cell... <td><div class="arrow-up"></div> + 1492.46</td> My goal is to have the arrow positioned to the left of the text and centered vertically wit ...

Retrieving Information from the Nextjs13 Server Component

Currently, I am developing a web application using NextJS along with MongoDB which is handled through Mongoose. Here is an overview of my Server Component: import { getPosts } from "@/lib/mongoDb/post"; import PostsClientComponent from "./PostsClien ...

Heroku Internal Server Error with NextJs version 5.0.0

Below are the scripts that I am using: "scripts": { "dev": "node server.js", "build": "next build", "start": "NODE_ENV=production node server.js", "heroku-postbuild": "next build" }, This is the content of my procfile: web: npm start ...

Adjust the clarity of the elements within my HTML document

I have been working on creating a login page that will appear in front of the main webpage. Through my online research, I discovered a technique to blur the main webpage background until the user logs in. Below is the code snippet: HTML: <div id="logi ...

"Exploring the Power of Jsoup for Selecting

I'm attempting to extract all the links nested within the div class news column index. Here is a snippet of the HTML structure: https://i.stack.imgur.com/zdFWS.jpg Below is the code I have used, but unfortunately, it's not yielding any results. ...

The command "react-scripts" couldn't be located in the current environment

Currently enrolled in a Udemy course that involves using create-react-app. However, I encounter an error when attempting to run npm start and/or yarn start. You can find the course here: Complete React Developer in 2020 (w: Redux, Hooks, GraphQL) To init ...

Customizing the default font color in Angular Material

I am currently navigating through theming in Angular Material and feeling a bit disoriented. I have implemented the prebuilt indigo-pink theme by importing it into my styles.scss as shown below: @import "~@angular/material/prebuilt-themes/indigo-pink.css" ...

Center align the text inside a table cell of a span that is floated to the right and has a varying

Struggling to align a span vertically in the middle with a different font size than its table cell. The goal is to have the following layout: | | | Measurement (font-size: 100%) unit (font- ...

Dynamic Display Picture Banner - Adjustable Layout

My home page features a full screen image header that I'm working to make responsive. The width of the image is being cut off on various screen sizes. I've attempted adjusting the height and width settings, but I want the image itself to resize ...

Is it possible for an HTML file to not recognize an external CSS stylesheet?

I've been trying everything, but I can't seem to get these two documents to work together. I'm confident that the CSS file is linked correctly with the right file name. I decided to give it a shot after watching this coding blog tutorial on ...

Modifying the color scheme of Bootstrap

In order to simplify referencing, I am establishing new theme colors as shown below, allowing me to use classes like bg-red instead of bg-danger or text-purple, and so forth. $primary : #24305e; $blue : #375abb; $indigo : #796eff; ...

Optimizing web layouts to fit on a single page is the most effective

Struggling to create a print layout for my web page that seamlessly transitions from the digital realm to the physical world. Utilizing HTML and CSS has presented challenges in aligning the "digital" design with a "real printable" page due to uncertainties ...

Alpinejs Mega Menu Issue: Hover Functionality Glitchy

I'm working on a complex Mega Menu project that is activated upon hovering, using the powerful combination of Tailwind CSS and Alpinejs. The functionality is mostly there, but I've encountered some bugs along the way. Despite my attempts to impl ...

Reorganizing MongoDB arrays with Prisma and NextJS

I'm dealing with data stored in MongoDB that looks like this: { items: [ { id: '6614005475802af9ae05b6b2', title: 'title', createdAt: '2024-04-08T14:33:56.734Z', }, { id: '6613f ...

Implementing a sorting feature in React with an icon

i have implemented a method called renderSortIcon, where i aim to display an icon. In this method, I have passed a parameter 'column'. However, when I try to access 'column.path', it throws an error stating that 'path' is not ...

Guide to incorporating HTML within React JSX following the completion of a function that yields an HTML tag

I am currently working on a function that is triggered upon submitting a Form. This function dynamically generates a paragraph based on the response received from an Axios POST request. I am facing some difficulty trying to figure out the best way to inje ...

React - Exploring the depths of functional components

Picture this: a straightforward form that showcases several unique components with customized layouts. The custom components include: <UsernameInput />, <PasswordInput />, <DateTimePicker />, <FancyButton />, <Checkbox /> Th ...