Search code examples
cssreactjslayoutgridmaterial-ui

Changing the order of Grid Item stacking in material-ui


I have a problem with the order of stacking of grid items whenever browser shrinks.

This is what I want on the normal desktop screen(lg):

---------------------------------------------
|   col 1     |         col 2       | col 3 |
---------------------------------------------

But After Shrinking the browser I am getting the following result:

-------------------------
|     col 1             |
-------------------------
-------------------------
|     col 2             |
-------------------------
-------------------------
|     col 3             |
-------------------------

Can I with material ui Grid layout achieve this on a mobile screen:

-------------------------
|     col 1             |
-------------------------
-------------------------
|     col 3             |
-------------------------
-------------------------
|     col 2             |
-------------------------

I have read articles on changing the order of CSS-grids for the same topic but how to achieve this using material-ui Grid layout.

Edit material-ui Grid Stacking


Solution

  • Extending to Olivier's answer Material-UI heavily uses the CSS flexbox layout within its implementation. As the documentation quotes

    A flex container is the box generated by an element with a computed display of flex or inline-flex. In-flow children of a flex container are called flex items and are laid out using the flex layout model.

    So Grid items are flex items and Grid Container is flexbox container in laymans language. Hence we can use the order property on Grid items to change their relative order of appearance when the Box or Grid Container resizes. So passing the style in the following manner to the grid item should work out

      itemStyle: {
        order: ${Desired_order_before_Shrinking},
    
        [theme.breakpoints.up(`${DesiredScreenSize}`)]: {
          order: ${Desired_order_after_Shrinking},
        },
     
      }
    

    Finally doing <Grid item xs={12} md={6} className={this.props.classes.itemStyle}> will reorder that item. Hope it creates better understanding.

    UPDATE: Material UI V5. Thanks to @Adam Cooper's answer below

    <Grid container spacing={2}>
      <Grid item md={12} lg={4} order={{ md: 1, lg: 1 }}>col 1</Grid>
      <Grid item md={12} lg={4} order={{ md: 3, lg: 2 }}>col 2</Grid>
      <Grid item md={12} lg={4} order={{ md: 2, lg: 3 }}>col 3</Grid>
    </Grid>