Home > Enterprise >  How to put Box in center of Flex when using Spacers
How to put Box in center of Flex when using Spacers

Time:01-20

So I have a header where I'm using Flex. In that header, there is an item I want to be aligned in the center of the header. Here is some example code demonstrating the

return (
  <Box>
    <Box paddingTop={5} paddingBottom={5} paddingLeft={8} paddingRight={8}>
      <Flex alignItems="center" gap="2">
        <Box p={4} w="200px" bg="red" />
        <Box p={4} w="200px" bg="blue" />
        <Spacer />
        <Box p={4} w="200px" bg="purple" />
        <Spacer />
        <Box p={4} w="200px" bg="green" />
      </Flex>
    </Box>
  </Box>
);

As you can see, I have two boxes on the left, one in the middle, and one on the right, and I'm using Spacers to separate these 3 groups. What I want is for the purple box to align itself in the center of the outer box, but as you can see below, it does not.

Purple box not in the middle

Instead, it creates two Spacers of the same width, which results in the purple box being aligned right of center.

While still using Flex and Spacer, how can I make the purple box align in the center properly, where the middle of the box aligns with the center of the outer box?

CodePudding user response:

One approach could be wrap the Box in 3 sections taking the same width in the container with flex-grow: 1, and center content in the middle section. This would also omit the use of Spacer.

Example: (demo on stackblitz)

<Box>
  <Box paddingTop={5} paddingBottom={5} paddingLeft={8} paddingRight={8}>
    <Flex justifyContent="center" alignItems="center" gap="2">
      <Flex alignItems="center" gap="2" flex="1" outline="3px solid hotpink">
        <Box p={4} maxW={"200px"} bg={"red"} flex="1 1" />
        <Box p={4} maxW={"200px"} bg={"blue"} flex="1 1" />
      </Flex>
      <Flex
        justifyContent="center"
        alignItems="center"
        gap="2"
        flex="1"
        outline="3px solid hotpink"
      >
        <Box p={4} maxW={"200px"} bg={"purple"} flex="1 1" />
      </Flex>
      <Flex
        justifyContent="flex-end"
        alignItems="center"
        gap="2"
        flex="1"
        outline="3px solid hotpink"
      >
        <Box p={4} maxW={"200px"} bg={"green"} flex="1 1" />
      </Flex>
    </Flex>
  </Box>
</Box>

CodePudding user response:

You can position the purple box in the center of the parent container with the following styles for the purple box:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

And add position: relative to the container

  • Related