Guide to aligning Material UI card in the center (React)

I've been struggling to find a solution for centering a Material UI card in React. Any assistance would be greatly appreciated! Thank you :)

link to image on website

<Grid container justify="center">
                        <Card sx={{ maxWidth: 345}} display="flex" alignItems="center"justifyContent="center">
                        
                        <CardMedia
                               
                                      component="img"
                                      height="140"
                                      image="astroline-white_betterq.png"
                                      alt="astroline banner"
                        />
                        
                        <CardContent>
                        <Typography gutterBottom variant="h5" component="div">
                        
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                        Astroline is a space / sci-fi game that explores an apocalyptic event on Earth.
                        </Typography>
                        </CardContent>
                        <CardActions>
                        <Button size="small" elevation="1" onClick={() => navigate("/astroline")}>Learn More
                        </Button>

                        </CardActions>
                        </Card>
                 </Grid>

Answer №1

To quickly center the content, you can use flexbox on the parent element. Simply add the following CSS to the parent class:

.parent-element-class {
    display: flex;
    justify-content: center;
}

Another option is to create a class for the MUI card and center it using traditional methods:

.mui-card-root-class-name {
  margin: 0 auto;
}

It really depends on how you are implementing MUI in your project, so it would be helpful to see some code.

You could also utilize Wrappers like:

https://mui.com/material-ui/react-grid/ or https://mui.com/material-ui/react-stack/

The documentation provided by Mui is quite thorough and helpful.

UPDATE: You may want to try adding width: 100% to the parent element to ensure proper centering.

Answer №2

If you want to center your content within a Grid, make sure to include the following code:

<Grid container justifyContent="center" >

Check out this codesandbox example for reference.

<Grid container justifyContent="center" >
  <Card
    sx={{ maxWidth: 345 }}
    display="flex"
    alignItems="center"
    justifyContent="center"
  >
    <CardMedia
      component="img"
      height="140"
      image="astroline-white_betterq.png"
      alt="astroline banner"
    />

    <CardContent>
      <Typography gutterBottom variant="h5" component="div"></Typography>
      <Typography variant="body2" color="text.secondary">
        Astroline is a space / scifi game about an apocalyptic disaster that occurred on Earth.
      </Typography>
    </CardContent>
    <CardActions>
      <Button
        size="small"
        elevation="1"
        onClick={() => navigate("/astroline")}
      >
        Learn More
      </Button>
    </CardActions>
  </Card>
</Grid>

Alternatively, you can use a Stack component instead of a Grid to wrap your Card.

<Stack  alignItems="center">... Your <Card> content  ... </Stack>

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

Unable to upload code onto GitHub due to the excessive size of node modules

I recently restructured my react project, separating the front-end code into a client directory while keeping the back-end code in the root directory. However, I encountered an issue when trying to push my code to GitHub. An error message indicated that th ...

bootstrap 5 with uneven spacing

I am working on some HTML/CSS code that utilizes Bootstrap 5.2 and the justify-content-between class in order to move two buttons to the edges of a container. <div class="container"> <div class="row"> <div cla ...

Creating an Art Deco inspired border using CSS

I am interested in creating a border effect using only CSS. Here is an image of the effect I am looking to achieve: https://i.sstatic.net/cKWXZm.jpg I would like to achieve this effect without adding additional div elements. Any suggestions or tips on how ...

The content security policy is preventing a connection to the signalr hub

Currently, I am developing an application using electron that incorporates React and Typescript. One of the features I am integrating is a SignalR hub for chat functionality. However, when attempting to connect to my SignalR server, I encounter the followi ...

Having trouble with the npm run eject command?

Encountering an issue post executing npm run eject in my React project. If anyone has a solution to this problem (refer to the error in the image), please let me know. https://i.stack.imgur.com/FkNOf.png Appreciate any help provided. Thank you! ...

Adding a command to open a new browser tab using JavaScript code can easily be accomplished by following these steps. By using Terminal, you can quickly and efficiently implement this feature

I'm new to coding and trying to create a terminal simulation. You can check out my code here: https://codepen.io/isdampe/pen/YpgOYr. Command: var coreCmds = { "clear": clear }; Answer (to clear the screen): function clear(argv, argc ...

Exploring Advanced Functionality in Next.js 14 - Chapter 12: Leveraging Forms for Server Interactions - Troubleshooting Issue with Form Submission and Server Actions

I have reached Chapter 12 of the official Next.js tutorial and I am currently working on the topic related to mutating data. If you want to follow along, you can find the tutorial here. After completing the "3. Extract the data from formData" section, I e ...

How to trigger a JavaScript function using a button click

I've been struggling to figure out why my JavaScript code isn't functioning properly within Ionic. Can anyone guide me on how to store a number in a variable, display that variable, and increment it when a button is clicked? I have successfully ...

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

Applying the Active CSS class to a Bootstrap Carousel

I'm currently working with a bootstrap carousel that displays dynamic images fetched from a backend API. The challenge I'm facing is that I'm unable to set the active class for the individual slides. If I hardcode the active class, all slide ...

The Recoil Effect is acting unusually

I'm diving into Recoil for the first time. Just created a sample form with 2 buttons - one for decreasing and one for increasing a counter. I decided to add an effect just to test it out, but strangely enough, the effect only triggers when I decrease ...

What is the method for displaying text instead of an item using state?

How can I ensure that only the single item I want to remove from my favorites list is replaced, instead of all items being eliminated with conditional rendering in React Native? import React, { useEffect, useRef, useState } from 'react' import { ...

What is the process for revoking a previous axios request?

Is there a way to cancel the initial axios request in React/Redux when a new request is made? I came across this solution online, but it doesn't seem to be working as expected. action.js class FilmsActions { getFilmList(searchParams = undefined, ...

What is the problem with locating elements in Selenium with Java?

I've been encountering difficulties in finding elements on a webpage structured like this: <tr id="filter100" style="...." idx=0 <td> <div onclick=... style=... <table dir = "fil"> <tbody> ...

Issue with session variable being recognized on the server side but not on the client side in NextAuth.js v4 beta

I am currently utilizing the beta version of NextAuth.js v4 to enable server-side rendering and incorporate sessions via props. Although the session data is successfully logged in the console from the getServerSideProps function within the index.js f ...

Issue with calling hooks. Hooks can only be invoked within the body of a function component

Looking to develop a todo application using React, but encountering an issue with the useContext hook. The error message "Invalid hook call..." suggests a few possible reasons for this problem: Possible mismatched versions of React and the renderer (e.g ...

How to redirect in Next.js from uppercase to lowercase url

I'm trying to redirect visitors from /Contact to /contact. However, following the instructions in the documentation results in an endless loop of redirects. This is my attempted solution: // next.config.js async redirects() { return [ { ...

I am experiencing an issue where the onChange event is not being triggered in my React application

I am currently in the process of creating a random football team picker and handling the database on my own. However, I seem to be encountering issues with the inputs. import React, { use, useRef, useState } from "react"; const fetchAll = async ...

Endless [React Native] onFlatList onEndReached callback invoked

Attempting to create my debut app using ReactNative with Expo, I've hit a snag with FlatList. The components are making infinite calls even when I'm not at the end of the view. Another issue might be related; across multiple screens, the infinite ...

Leverage parameters in React Router to redirect

Is there a way to redirect from /web/ or /beta/ to /web/dashboard or /beta/dashboard/, respectively? I attempted the following method... <Redirect exact from="/:platform(web|beta)" to="/:platform/dashboard" /> The issue is that when I visit www.ab ...