Display Inline-block and hover poblem. Help?

Whenever I hover over #div1 or #div2, it should perform it’s transition of going down via margin-top transition without any issues. Although in my scenario, when I hover over #div1 or #div2, it goes down along with other div, which is not supposed to be.

i am confused why it is happening?

please help. :point_down: :point_down:

CodePen Link

If you remove display: inline-block you’ll notice that when you hover over the red one both of the divs move, but if you hover over the green one only the green one moves. That’s because the red one is pushing down on the green one because of its position in the DOM. Moving the red one affects the positioning of the green one.

Using display: inline-block does not change this. In fact, it makes it “worse” in that they are both now on the same line, so when you hover over one of them, the entire line moves down, so that’s why both of them are moving down regardless of which one you hover over.

If you want them to work independently then you need to remove them from the natural flow. You might look into absolute positioning to do that.

You can use a transform translate instead of the margin as well.

transform: translateY(600px);

But it’s still going to be driven by the hover which makes it awkward.

You can use JS to do the animation.

const redBox = document.getElementById("div1");

const moveDown = [
  {
    transform: "translateY(600px)",
    borderRadius: "50%",
    backgroundColor: "aqua"
  }
];

const timing = {
  duration: 2000,
  iterations: 1,
  fill: "forwards"
};

redBox.addEventListener("mouseover", () => {
  redBox.animate(moveDown, timing);
});

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.