reactjsmaterial-uiframer-motion

Div moving in front of absolute element when hovered


I am creating a component where I have two divs (using MUI Box) sitting behind an absolute positioned div. Everything is positioned in a manner that the absolute div is sitting in the center and you can view the edges of the two divs behind. When you hover the divs I have them set to increase the scale by 1.2 which works fine for the div in the back left but when I hover the one on the back right it appears in front of the center div. I am using Material UI components a long with framer motion for the animations

<div className="App">
      <Box
        sx={{
          display: "flex",
          flexDirection: "row",
          width: "100%",
          height: "500px",
          justifyContent: "space-around",
        }}
      >
        <Box
          component={motion.div}
          whileHover={{
            scale: 1.2,
          }}
          sx={{
            display: "block",
            width: "40%",
            height: "40%",
            backgroundColor: "blue",
          }}
        />
        <Box
          component={motion.div}
          sx={{
            width: "60%",
            height: "30%",

            position: "absolute",
            backgroundColor: "red",
          }}
          initial={{
            opacity: 1,
            scale: 1,
          }}
          whileHover={{
            scale: 1.1,
          }}
          animate={{}}
          transitiion={{
            duration: 0.5,
            ease: "easeInOut",
          }}
        />
        <Box
          component={motion.div}
          whileHover={{
            scale: 1.2,
          }}
          sx={{
            display: "block",
            width: "40%",
            height: "40%",
            backgroundColor: "blue",
          }}
        />
      </Box>
    </div>

EDIT Here is the link to an example of the issue in code sandbox Framer motion hover issue


Solution

  • This is happening because the last box is created after the middle box in your html. That's the proper way to do it, but if they both have the same z-index, the later box will appear on top. I'm not sure exactly what's causing the hover transition to appear on top of the absolutely positioned box, but I'm almost sure it has something to do with the fact that the middle box is absolutely positioned. Without the absolutely positioned box, the latter box should appear on top all of the time, not just when hovered. While it's a bit mysterious, you can get around this by just applying a z-index to the middle box that's greater than 1.