Home > Software engineering >  How to get a fixed gap between flex items using justify-content: space-between?
How to get a fixed gap between flex items using justify-content: space-between?

Time:01-24

I have a MUI container with dynamic values in it, coming from redux state. Container has the timer, the score and the lives in it. When they change e.g timer goes to single digits, the space between them is altered. How can I have the gap between them fixed? This is what I have currently:

function gameInfo() {
  return (
    <>
      <Container
        sx={{
          width:'100%',
          borderRadius: '16px',
          display: "flex",
          flexDirection: "row",
          justifyContent: "space-between",
        }}
      >
        <Seconds></Seconds>
        <Points></Points>
        <Lives></Lives>
      </Container>
    </>
  );
}

export default gameInfo;

CodePudding user response:

It would be largely depending on the styles of the custom components like Seconds, but in general, if the goal is to keep the three components at left end, middle, and right end, consider to wrap the components for the sides in a container with flex: 1 to take the available space, and align the content to the matching side.

Demo of simplified example: stackblitz

import { Box, Stack, Typography } from "@mui/material";

function GameInfo() {
  return (
    <Stack direction="row" alignItems="center">
      <Box sx={{ display: "flex", flex: "1", justifyContent: "flex-start" }}>
        <Seconds />
      </Box>
      <Box sx={{ display: "flex", justifyContent: "center" }}>
        <Points />
      </Box>
      <Box sx={{ display: "flex", flex: "1", justifyContent: "flex-end" }}>
        <Lives />
      </Box>
    </Stack>
  );
}
  • Related