The art of perfect alignment: Mastering the positioning of Material-UI Grid

This issue has been resolved

Hey there, I'm currently working on a React App with Material-UI and I'm trying to center a Grid item that includes a Card along with two additional Grid items. Below is the relevant code snippet. Although the Cards do show up in the middle of the screen, they're not perfectly centered and it's bothering me quite a bit.

Screenshot:

Key code:

render() {
    return (
      <Grid container>
        <Grid item xs={12}>
          <Typography variant="h3" gutterBottom>
            My Projects
          </Typography>
        </Grid>
        <Grid item xs={6} justify="center">
          <Grid item xs={12}>
            <Card>
              <CardMedia
                component="img"
                height="140"
                image="https://github.com/dbarnes18/Portfolio/blob/master/assets/images/spotter.png?raw=true"
                alt="Spotter"
              />
              <CardContent>
                <Typography gutterBottom variant="h5" component="div">
                  Spotter
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  Spotter is an easy-to-use Spotify music controller with
                  functioning room and voting systems.
                </Typography>
              </CardContent>
              <CardActions>
                <Button
                  size="small"
                  color="primary"
                  to="/project/spotter"
                  component={Link}
                >
                  Read More
                </Button>
              </CardActions>
            </Card>
          </Grid>
          <Grid item xs={12}>
            <br />
          </Grid>
          <Grid item xs={12}>
            <Card>
              <CardMedia
                component="img"
                height="140"
                image="https://github.com/dbarnes18/Portfolio/blob/master/assets/images/impulse.png?raw=true"
                alt="Spotter"
              />
              <CardContent>
                <Typography gutterBottom variant="h5" component="div">
                  Impulse
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  Impulse is a macOS Virtual/Voice Assistant!{" "}
                  <i>Impulse is a little buggy and slow.</i>
                </Typography>
              </CardContent>
              <CardActions>
                <Button
                  size="small"
                  color="primary"
                  to="/project/impulse"
                  component={Link}
                >
                  Read More
                </Button>
              </CardActions>
            </Card>
          </Grid>
        </Grid>
      </Grid>
    );
  }

System Details:

Google Chrome: 93.0.4577.82 (Official Build) (x86_64)
Revision: e3a25d9b9e2d0b728e045ec87c0aa4942aa46e4e-refs/branch-heads/4577@{#1237}
OS: macOS Version 10.15.7 (Build 19H1417)
JavaScript: V8 9.3.345.19

Thank you!

Answer №1

To implement material-ui, simply include the necessary styling in your code.

This example uses material-ui version 4.12.3

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles(() => ({
  root: {
    display: "flex",
    justifyContent: "center",
    alignItem: "center"
  }
}));

Add the custom styles to the Grid component:

export default function App() {
  const classes = useStyles();
  return (
    <Grid container className={classes.root}>
           ....
)}

Explore the live demo here

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

Storing multilingual JSON data in AngularJS for faster access

I have successfully implemented a multi-language concept in my application, but I am facing an issue where the language (.json) file is being loaded for every field. As a result, the application takes a longer time to load. My requirement is to load the .j ...

What is the best way to send props to a component that is exported using a Store Provider?

I'm trying to export my react component along with the redux store Provider. In order to achieve this, I've wrapped the component with an exportWithState callback. However, I'm facing an issue where I can't seem to access the props that ...

Please include the document with a name that contains spaces

I am facing an issue where I cannot attach files with spaces in the name. However, when a file with no space in the name is successfully attached. I am using CodeIgniter for this purpose, uploading the file to the server before attaching it. I use the help ...

Utilizing JQuery's printThis Plugin in Combination with the Style Attribute

I am currently working on a JavaScript app and I am trying to implement a button that will allow users to print a specific div. To achieve this, I am utilizing a jQuery plugin called printThis (github link) as well as attempting to use window.print(). $(" ...

Using flexbox to adjust the height of a block in the layout

Is there a way to modify the height of .half-containers1 and .half-containers2? Additionally, how can I create the triangle shape that is shown in the image? Is it achievable with CSS alone or do I need to use an image? Check out my fiddle for reference ...

Ways to authenticate custom kinds in JSON schema?

When working with JSON Schema, one of the challenges I have faced is the limitation on supporting ‘double’ and ‘float’ types for numeric values. While using AJV in JavaScript to validate a schema, it fails due to this restriction. Is there a way to ...

Issues with Passing Props for Mutation and Query Components- OR -Mutations and Queries

Whenever my handler is triggered, an error pops up stating that the mutation is not a function. Strangely, I noticed that my mutation and query are not being linked to my component when I check this.props. ERROR: RelationshipDropDown.js:58 Uncaught Type ...

Tips for creating a fluid slide-up animation

I've been tasked with creating a multi-step accordion similar to a stepper form. Each accordion will contain forms with next and previous buttons inside. When the next button is clicked, a new accordion will open from the bottom of the page, initial ...

Embracing async-await while awaiting events in node.js

I am attempting to incorporate async await into a project that is event-driven, but encountering an error. The specific error message I am receiving is: tmpFile = await readFileAsync('tmp.png'); ^^^^^^^^^^^^^ SyntaxError: Unexpec ...

What role does AppProps play in the Next.js framework?

As I delve into next.js, I stumbled upon the following snippet in the _app.tsx file: import type { AppProps } from 'next/app' function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } export default MyAp ...

JavaScript code to verify if a checkbox is selected

Having some trouble making a text box value change based on checkbox status. I've attached a function to the onclick event of the checkbox, but it's not quite working as expected. <div> MyCheckbox <input type="checkbox" id="Check1" name ...

Adjust Font Size inside Circular Shape using CSS/jQuery

I have been searching for different libraries that can resize text based on the size of a container. However, my container is circular and I am facing difficulty in preventing the text from overflowing beyond the border. Below you will find a Fiddle conta ...

Resolving the non-null assertion error in TypeScript and React: A step-by-step guide

My code snippet is as follows: type ItemProps = { status?: string; } <Items status={status!} /> // encountering an error with a warning about forbidden non-null assertion // @typescript-eslint/no-non- ...

Learn how to generate a dynamic pie chart in PHP that can adjust its sections based on the user's input, giving you a fully customizable data visualization tool

let userData = [ { label: "History", data: 90 }, { label: "Science", data: 85 }, { label: "Art", data: 95 }, ]; I have written this javascript code to represent the user's data, but I want it to be more flexible an ...

Is the `beforeEach` function in Jasmine synchronized?

Is it guaranteed that multiple beforeEach functions will always run sequentially? beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); It appears they do. I conducted a tes ...

Switch between divs based on the current selection

var header = $("#accordion"); $.each(data, function () { header.append("<a id='Headanchor' href='javascript:toggleDiv($(this));'>" + this.LongName + "</a>" + "<br />", "&l ...

Is there a way to pull information from a string and organize it into a two-dimensional array?

Utilizing the axios library, I am pulling data from a website. Unfortunately, the data being fetched is in HTML format. The extracted data looks like this: 1 Agartala VEAT 120830Z 23004KT 5000 HZ SCT018 SCT025 34/27 Q1004 NOSIG= 2 Ahmedabad VAAH 120830Z 23 ...

Experience the smooth CSS3 transition effects on iOS devices such as iPhones and iPads. Elevate the appearance of DOM objects with

I have a basic image contained within a div tag. I use JavaScript to add a transition effect to the div element: <div style="transition: opacity 0.8s linear; opacity: 0.5;"><img src="..." /></div> At the end of the transition duration ...

Troubleshooting Problem with Retrieving Files Using jQuery Ajax

I am attempting to use ajax to retrieve the contents of a file, but it doesn't seem to be functioning properly. I'm not sure why this is happening, as I have copied the same code from the examples on w3schools.com. $().ready(function(){ ...

Despite being initialized previously in JavaScript, the attribute of the object is still showing as undefined

After using an attribute from an Object multiple times, it suddenly appears as undefined when I call it in another function. Even though I have checked its values with console.log and they seem to be assigned correctly. Can anyone help me figure out what I ...