Home > Blockchain >  Avoid Absolute Position in Css in Material-UI and React
Avoid Absolute Position in Css in Material-UI and React

Time:10-27

How do I avoid using position: absolute for the "Hello There" button? The layout should stay the same. I just want to get rid of that css property. Is better approach? Pls fork my codesandbox below:

CODESANDBOX -----> CLICK HERE

<MainContainer>
  <Stack spacing={1}>
    {products?.map((product) => (
      <ProductItem
        key={product.id}
        name={product.name}
        description={product.description}
      />
    ))}
  </Stack>
  <Stack
    alignItems={"center"}
    sx={{
      marginTop: 2,
      position: "absolute",
      display: "flex",
      left: 0,
      right: 0
    }}
  >
    <Button variant="outlined" sx={{ bgcolor: "white" }}>
      Hello There
    </Button>
  </Stack>
</MainContainer>

CodePudding user response:

Kind of a non answer but, you probably shouldn't. Making a fully relative layout in this situation would requiere a layout that is a lot more complicate, where your dotter border would exist in a "layer" behind. And even then, to make that "layer" you would use a div that HAS absolute position.

Your use of position absolute here seems very correct, it is responsive, self contained, and used exactly for the type of things position absolute is ACTUALLY designed to solve.

Do you have a particular reason to want to remove the absolute position? If it's bringing any negative effects maybe they can be mitigated some other way.

CodePudding user response:

You could replace it with position: relative and top, but not sure if that's what you're going for.

  <Stack alignItems={"center"}>
    <Button variant="outlined" sx={{ bgcolor: "white", position: 'relative', top: 50 }}>
      Hello There
    </Button>
  </Stack>

Could you please elaborate on what result you want to accomplish?

I would recommend using position: absolute as you were. It's a perfect usage of it currently when you want to layer something on top without expanding the underlying box model.

  • Related