Plumpie
Plumpie

Reputation: 466

MaterialUI: how to position items inside grid item?

What would be the best way when working with MaterialUI to position an image inside a <Grid item>?

This could just be done by putting a div in the grid item, making it 100% width/height, applying flexbox, then do align-items and justify-content but I think that defeats the whole purpose of the Grid system, I'm thinking it shouldn't be that much code to position something inside the Grid.

example: https://codesandbox.io/s/nervous-lamport-rvrm5?file=/src/App.js

Upvotes: 0

Views: 1364

Answers (1)

somallg
somallg

Reputation: 2033

The main benefits of Grid is you have:

  1. Flexible Grid system with 12 col
  2. Responsiveness
  3. React-style syntax (props)
  4. Custom layout with CSS flex syntax

But deep down its still using CSS flex for layout

If it were CSS, to center an element inside a div container, you just need to:

  1. Make the container display: flex
  2. Add justify-content: center to container

With that in mind, we can translate to Grid with

  {/* Lets try to center the photo */}
  <Grid item container xs={6} justify="center">
    <img src="https://picsum.photos/100" alt="placeholder"></img>
  </Grid>

container is to add display: flex to Grid

justify="center" is to add justify-content: center to Grid

Output:

enter image description here

No more className and more React props.

Upvotes: 1

Related Questions