Dave
Dave

Reputation: 19090

How do I vertically align my items in a material-UI Grid row?

I'm using Material UI's Grid component to display three items in a row. I would like to vertically align the items to the center, but I'm having a disappointingly challenging time doing this. Evidently "justifyContent: 'center'," only horizontally centers items. I discovered this

const styles = (theme) => ({
  root: {
    textAlign: "left",
    margin: theme.spacing(2),
    paddingBottom: theme.spacing(1),
    color: theme.color.secondary,
  },
  cardHeader: {
    paddingBottom: theme.spacing(0),
  },
  cardContent: {
    width: "100%",
    paddingBottom: theme.spacing(1),
  },
  rowBody: {
    width: "100%",
    flexWrap: "nowrap",
    alignItems: "center",
    justifyContent: 'center',
  },
...
      <CardContent className={classes.cardContent}>
        <Grid container className={classes.rowBody} spacing={1}>
          <Grid item>
            <img height="20" src={require('../../img/apple.svg')} alt="" />
          </Grid>
          <Grid item>
            {title}
          </Grid>
          <Grid item className={classes.infoIcon}>
            <InfoIcon />
          </Grid>
        </Grid>

produces the below.

enter image description here

How can I vertically align my items without horizontally aligning them?

Upvotes: 4

Views: 16113

Answers (2)

Quentin Grisel
Quentin Grisel

Reputation: 4987

[Edit]: Based on Kiril answer (thx for the sandbox), here is what i was thinking about :

import React from "react";
import { Grid } from "@material-ui/core";
import { Error } from "@material-ui/icons";

export default function App() {
  return (
    <Grid container spacing="1" alignItems="center">
      <img
        src="https://yt3.ggpht.com/a/AATXAJxK3dHVZIVCtxjYZ7mp77wBbCs9fw4zU46V_Q=s288-c-k-c0xffffffff-no-rj-mo"
        alt="no-src"
        height="20px"
      />
      <span style={{ padding: 5 }}>no title supplied</span>
      <Error />
    </Grid>
  );
}


Can't you put your three elements in the same grid ? It would be easier to do so and your actual code would works.

If not, your grid may be aligned but the content isn't because it's not a direct child of a flex container. try adding a display: table-cell; verticalAlignment:center to your grid item (or its content by wrapping it in a div with width and height to 100%)

Upvotes: 4

Kirill Skomarovskiy
Kirill Skomarovskiy

Reputation: 1565

Svg and img elements have display: inline-block. Inline-block has a bottom gap. You just need to change the display to block.

I've created Sandbox as example

Upvotes: 4

Related Questions