What is the best way to align an avatar within a cardHeader component in the center?

Recently, I've been working on a frontend project using Material UI. In my design, I have cards that display data, and I wanted to include an avatar in the center of each card. Despite using a card header to insert the avatar, I struggled to align it properly. I attempted setting alignContent and textAlign to center within the media style class, but unfortunately, it didn't do the trick.

Any suggestions on how I can achieve this desired center alignment? Should I consider utilizing something other than the cardHeader?

<CardHeader
     className={classes.media}
     avatar={<Avatar alt="Alias" src={alias1} className={classes.small} />}
   />

Update: Ultimately, I was able to center the avatar by specifying marginLeft and marginRight as 'auto' within the "small" class. However, the accepted solution also proved effective.

Answer №1

CardHeader requires a title, styled with flex: 1 1 auto, even if the title prop is not provided, preventing the use of justifyContent in the media class styles.

There are various ways to tackle this issue, but if you are not utilizing other props of CardHeader, it's recommended to replace it with Box or Grid.

const {Card, Box, Avatar, CardContent, Typography, makeStyles } = MaterialUI

const useStyles = makeStyles({
  root: {
    backgroundColor: "#eeeeee",
    maxWidth: 400
  }
});

function MyCard() {
  const classes = useStyles();

  return (
    <Card className={classes.root}>
      <Box display="flex" justifyContent="center" alignItems="center" p={2}>
        <Avatar alt="Alias" className={classes.small} />
      </Box>
      <CardContent>
        <Typography variant="body2">
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Impedit modi
          delectus laudantium neque perspiciatis voluptate aut aliquam tempore
          atque nobis.
        </Typography>
      </CardContent>
    </Card>
  );
}

ReactDOM.render(<MyCard />, document.getElementById('root'))
<script src="https://unpkg.com/react@latest/umd/react.development.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/react-dom@latest/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/babel-standalone@latest/babel.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<div id="root"></div>

Answer №2

Give this a shot

style={{ alignItems: "center", display: "flex" }}

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

Can the data retrieved from a jsonp call that may be considered "bad" be utilized effectively?

When making a JSONP call to another domain, I am receiving data that is in JSON format but not wrapped in a function. This causes a parse error to occur. However, the data is still retrievable and visible. Despite the error, is it possible to utilize the ...

Converting images to greyscale or transparency within a ReactJS component

I am exploring ways to transform an image into grayscale or make it transparent before using it as a background in ReactJS. Is there a way to achieve this in ReactJS? My current code snippet is shown below: <GridListTile> <img style={{ -we ...

Troubleshooting CSS Carousel Navigation Problems

{% extends 'shop/basic.html' %} {% load static %} {% block css %} .col-md-3 { display: inline-block; margin-left:-4px; } .carousel-indicators .active { background-color: blue; } .col-md-3 img{ width: 227px; ...

What is the process for linking my Next.js application with MongoDB Compass?

Currently, I am working on a project in Next.js called NetMapper where I am developing a web interface for the CLI tool nmap. My main focus right now is creating Sign In/Sign Up forms and storing user information in MongoDB Compass. Despite trying various ...

Encountering an issue when attempting to host a Next.js application on Vercel

Why is it important to regularly do this task as per the instructions provided in the link? Info - Working on creating a highly efficient production build... Note: Next.js now collects completely anonymous telemetry data on user usage. This data helps sha ...

Testing the functionality of an Angular service using unit tests

Confused about how to test a service in an Angular project that involves a small class with an observer? Can't seem to figure out why the test fails when calling the 'pop' method. Want to ensure that the public methods of this class perform ...

When using NextJs with Material UI, manually refreshing the page may trigger a warning message stating: "Prop `className` did not match. Server: `MuiTypography-root MuiLink`."

In my Next.js project with Material UI, I am facing an issue where hot reloading works fine when I make changes and run the server. However, if I manually refresh the page, all the styles get messed up and I receive a warning saying: Warning: Prop classNam ...

Tips on accessing close autoComplete/TextField title in AppBar

Looking to add a search bar and login button in the AppBar, where the search Bar is positioned close to the title. The desired order for the AppBar components should be as follows: Title SearchBox LoginButton How can this be achieved? Below is th ...

Manipulating AngularJS variables that are outside of its designated scope should be restricted

Something strange is happening in my code. I created a function called "insertTstData" outside of any angular scope, and when it is called from another function named "save" within a controller named "remark", it somehow manipulates a local variable and th ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

Do developers only need type definitions for npm packages on their local machines?

It is my understanding that type definition modules for npm packages offer developers intellisense, eliminating the need to guess parameter types when using library methods. These modules have proven to be extremely valuable in my typescript project, esp ...

Tips for resolving the error "Module not found: Unable to locate '@babel/runtime/core-js/map' in Material-UI"

While working with React using Material UI, I recently updated Material-UI to the latest version and encountered the following error: ../node_modules/material-ui/styles/withStyles.js Module not found: Can't resolve '@babel/runtime/core-js/map&a ...

In my code, I never use the term "require", yet webpack continues to generate the error message "require is not defined."

I am in the process of developing an electron app using react. To run the development version, I use the following command: webpack-dev-server --hot --host 0.0.0.0 --port 4000 --config=./webpack.dev.config.js Displayed below is the webpack.dev.config.js ...

Tips for preventing a div from overflowing in col-md-12 in Bootstrap 3

Is there a way to maintain the same width for the image and div below? Everything looks good until the window size is between 545px to 575px. The .header width changes only at col-md-12. How can I preserve the aspect ratio? VIEW SCREENSHOT CODEPEN LINK ...

Achieving vertical center alignment in React Native: Tips and techniques

Just a quick heads-up: This question pertains to a school project. I'm currently knee-deep in a full-stack project that utilizes React Native for the front-end. I've hit a bit of a snag when it comes to page layout. Here's the snippet of my ...

Guide to retrieving fresh information from an API using a desktop application built on node and electron

Looking for advice on efficiently retrieving new order data from the Shopify API for a private desktop application I'm working on. Should I query the API at regular intervals while the application is active, or is there a way to implement webhooks in ...

Ensure that all form fields are completed and accurate before the Stripe payment modal is displayed

I've encountered an issue where the stripe payment modal appears before my form validation is complete. I am using the jQuery validation plugin for this purpose. I attempted to integrate the Stripe code within the submitHandler function, but it did no ...

"JQuery's selector is failing to locate elements once they have been loaded through an

I am facing an issue where jQuery selectors are not working on elements loaded from the server via Ajax requests, but they work fine in normal mode. $('#myid').change(function(){ alert('OK!'); }); <select id="myid"> <optio ...

Animate.css plugin allows for owl-carousel to smoothly transition sliding from the left side to the right side

I have a question regarding the usage of two plugins on my website. The first plugin is Owl Carousel 2, and the second one is Animate.css. While using `animateIn: 'slideInLeft'` with Owl Carousel 2 is working fine, I am facing an issue with `ani ...

What signals can indicate that the dispatch function has been triggered in Redux, even if the props remain unchanged?

I am facing an issue with my login page where I send login details to the server upon form submission. The server responds with either an access token or an error message. In both scenarios, I dispatch either loginSuccess or loginFailure respectively and ...