Tom el Safadi
Tom el Safadi

Reputation: 6746

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

I am using the React Material UI Grid System to align my elements on the page which uses flexboxes internally.

Everything works great but I cannot figure out how to horizontally align items when the containers contain a different number of items.

In the following example, I have 2 container items that take a width of 6 each. The first one contains items x1 and x2 and the second container contains the items y1, y2 and y3. As you can see, the way it looks right now is a little bit odd. I want x1 horizontally aligned with y1 and the same goes for x2 and y2.

The reason why I placed x1, x2 in the first container and y1, y2, y3 in the second container is because they semantically belong together. Thus, I can give the outer container different xs, sm, md, lg, xl values and if it hits the breakpoint, they will still show up in the correct order.

However, if I simply place them in 3 rows with 2 columns each, they will break in the order x1, y1, x2, y2, ... That would obviously not be right.

Therefore, my question is, how can I horizontally align them?

Edit:

This is how it looks right now:

enter image description here

This is how it want it to look like:

enter image description here

Upvotes: 4

Views: 2623

Answers (1)

ctrlaltdeleon
ctrlaltdeleon

Reputation: 406

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>
  );
}

Codesandbox Demo

Upvotes: 4

Related Questions