Search code examples
htmlcssreactjsmaterial-uigrid-layout

Grid layout with a row with 3 items that the width of each item is auto


I have problems achieving this layout:

layout

layout schema

I need that the width of the right and left elements be automatic and cover all the empty space on the right and the left of the element that is on the center.

This is the closest thing that I could do, but the problem is that the width of the item of the center is fixed to 2 of the 12 units of the container and the right and left lines are fixed to 5 units each one

<Grid container direction='row' alignItems='center' justify='center' style={{ width: '100%', textAlign:'center' }}>
    <Grid item xs='5'>
        <Divider />
    </Grid>
    <Grid item xs='2'>
        <span>or</span>
    </Grid>
    <Grid item xs='5'>
        <Divider />
    </Grid>
</Grid>

I'm using the material-ui reactjs library. Can anyone help me? I'm open to help either using mterial ui library or with a css/js answer


Solution

  • Instead of using explicit column widths (like xs='5') you could use "Auto layout" columns by just specifying xs for the items that need to stretch (aka flex-grow: 1) all the way through. Do not set it for the middle item with text so that it does not stretch and it would retain auto width. The solution can be found in the snippet below.

    const { Grid, Divider } = MaterialUI;
    
    function App() {
      return (
    <Grid
      container
      direction="row"
      alignItems="center"
      justify="center"
      style={{ width: "100%", textAlign: "center" }}
    >
      <Grid item xs>
        <Divider />
      </Grid>
      <Grid item>
        <span>or</span>
      </Grid>
      <Grid item xs>
        <Divider />
      </Grid>
    </Grid>
      );
    }
    
    ReactDOM.render(<App />, document.querySelector("#app"));
    <script src="https://unpkg.com/react@18.2.0/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
    <div id="app"></div>