Home > database >  React Material UI Grid Horizontally Align Items for Containers With Different Number of Items
React Material UI Grid Horizontally Align Items for Containers With Different Number of Items

Time:09-29

I am using the React Material UI Grid System to allign my elements on the page which uses flexboxes internally. Everything works great but I cannot figure out how to horizontally allign items when the containers contain a different number of items. In the following enter image description here

This is how it want it to look like: enter image description here

CodePudding user response:

We want to add props to the <Grid> to make this possible.

  1. alignItems="flex-start" will allow grid items to stick to the top then fall towards the bottom.
  2. direction="column" will change the flow of how items are "stacked" in a sense. This will change the sizing of the container and items that it is attached to so expect some xs={12} to turn into xs={6} and vice versa.

Here's the example code below as well as its implementation via sandbox.

import "./styles.css";
import { Grid } from "@material-ui/core";

export default function App() {
  return (
    <div className="App">
      <Grid alignItems="flex-start" container spacing={1}>
        <Grid container direction="column" item xs={6} spacing={1}>
          <Grid item xs={12} style={{ border: "1px solid black" }}>
            x1
          </Grid>
          <Grid item xs={12} style={{ border: "1px solid black" }}>
            x2
          </Grid>
        </Grid>
        <Grid container direction="column" item xs={6} spacing={1}>
          <Grid item xs={12} style={{ border: "1px solid black" }}>
            y1
          </Grid>
          <Grid item xs={12} style={{ border: "1px solid black" }}>
            y2
          </Grid>
          <Grid item xs={12} style={{ border: "1px solid black" }}>
            y3
          </Grid>
        </Grid>
      </Grid>
    </div>
  );
}

Working example.

  • Related