Mohammed Hammad
Mohammed Hammad

Reputation: 43

How do I center an avatar element that is within a cardHeader component?

I am using material ui for a frontend project and I have cards that display data. I want to display an avatar in the card in the center. I am using a card header to insert my avatar but am not able to center it. I tried setting alignContent and textAlign to center in the media style class but that doesn't helps.

What should I do to achieve that center alignment? Let me know if I should be using something other than the cardHeader.

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

Update: I got the result by specifying marginLeft and marginRight to be 'auto' in the "small" class. But the accepted answer also works.

Upvotes: 3

Views: 1853

Answers (2)

hotpink
hotpink

Reputation: 3226

CardHeader is expecting a title, which is rendered with a flex: 1 1 auto style, regardless of whether you provide the title prop or not. That's what's stopping you from using justifyContent in your media class styles.

There are several ways to approach this, but if you don't make use of other CardHeader props, I would simply 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>

Upvotes: 4

Mohammad Hashemi
Mohammad Hashemi

Reputation: 647

Try this

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

Upvotes: 0

Related Questions