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

What is the best way to keep only the arrow controls visible in TransformControls translation mode?

Currently, I am using TransformControls which meets my requirements. However, it includes extra elements such as arrows and squares around the object. Is there a way to disable these additional elements and only display the arrows? https://i.sstatic.net/Lk ...

I attempted to verify the login through postman, but encountered an error in the process

I created the login route on the backend and tested it in Postman, but encountered this error message: https://i.stack.imgur.com/PdyCo.png Below is the code for the login route: router.post("/login", async (req, res) => { try { const user = await ...

How can I access the parent elements within a recursive directive?

I'm currently implementing a recursive directive called https://github.com/dotJEM/angular-tree to iterate through a model structure like the one below: $scope.model = [ { label: 'parent1', children: [{ ...

Revolutionary AJAX technology seamlessly updates and refreshes elements within every row or form on a webpage

<script type="text/javascript"> $(document).ready(function() { $("#submit<?php echo $resultshome['hskid']; ?>").click(function() { $.ajax({ type : "POST", url : "/scores/printPOST.php", data : { "subro ...

Managing the relationship between two asynchronous thunks

Two async thunks have been created using the createAsyncThunk() function from the redux-toolkit. For example: const getOrder = createAsyncThunk('a/getOrder', async (_, thunkAPI) => { // `userId` is obtained from API.getUser() // Attempted ...

Using Express.js to leverage Vega for generating backend plots

Exploring ways to create plots using backend code and transfer them to the front end for display. Could it be feasible to generate plots on the server-side and then transmit them to the front end? I am interested in implementing something similar to this: ...

Morris.js tutorial: Enhancing bar charts with data labels

I have this: https://i.sstatic.net/GXjur.png But I want this instead: https://i.sstatic.net/spcS2.png Does morris.js support this feature? If not, what would be the most effective method to implement it? ...

Create a moving background gradient with styled-components

Currently, I am working on setting the background of the <Paper /> component using Material-UI version 1.0.0-beta.25 to display a gradient of colors. The colors are dynamically added by clicking the Add button and selecting one from the color picker. ...

Troubleshooting the issue of post-initialization store updates not functioning in AlpineJS

When setting up a store, I initially use: document.addEventListener('alpine:init', () => { Alpine.store('selectedInput', 0) }) However, when attempting to update selectedInput within a function later on, it doesn't reflect th ...

Are JSON-Web Tokens (JWTs) used for both verifying identity and granting access privileges?

Currently, I am exploring the process of developing a blog website that permits users to log in and perform tasks such as editing or deleting their own blogs based on their user role. If a different user logs in and does not own a particular blog, they s ...

Error Found in Angular2 Console Inspection

So, when I check the webpage inspection console, I see this error: Uncaught SyntaxError: Unexpected token { at Object.<anonymous> (main.bundle.js:3885) at __webpack_require__ (polyfills.bundle.js:51) at eval (eval at <anonymous> (m ...

Difficulty with Vue.js updating chart JS label names

I have been working with Vue JS and implementing a chart in my single page application. However, I am encountering difficulties updating the Legend and despite numerous attempts and searches, I am unable to get it to update. Any assistance in correcting my ...

Verify if the element in the array is set to true

Using a simple boolean in a condition is straightforward : var running = true; if(running) {/*do something*/} But what about using a boolean array? Can it be done like this: var running = [false,false,true,false]; if(running[]){/*do something*/} Curren ...

Ways to display a red alert message below an input field in React and Next.js when the input value is incorrect

<input aria-required className="bg-white text-black h-40px text-lg hover:border-blue-400 border-solid border-b-2 w-[87%] " id="" placeholder="" ...

Transferring previously obtained data to templateProvider within AngularJS

I'm currently working with AngularJS 1.3 and UI-Router. I have a state set up with a resolve and a templateProvider. My goal is to utilize the data fetched from the database in the resolve within the templateProvider without having to make duplicate ...

Can Glychicons be utilized in form submission buttons?

While I can easily create buttons with glyphicons using the <a class="btn...", I'm facing an issue when trying to do the same with <input type="submit" class="btn btn-default" value="" />. Instead of displaying the button, it appears blank. ...

Removing a row from a table in a React component

I have incorporated a Table component from Material UI into my project to display data fetched from an external API. The table dynamically updates its rows based on events received through a web socket connection. One specific requirement I have is that wh ...

RegEx in JavaScript to identify and match the innerHTML property of all elements

I am currently in the process of developing a Chrome extension that needs to identify specific pages within a website, including the Log In / Sign In page, the Sign Up / Register page, the About page, and the Contact Us page. My approach involves obtainin ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

Encountering a 404 error when translating URLs in Next.js i18n?

I am developing a multilingual service utilizing next-i18next. I wanted to have some of my routes translated as well, for example: EN: /contact => default language IT: /fa/ارتباط-با-ما => second language To achieve this, I utilized tran ...