Can anyone help me to create a translation transition on hover in the div when the cursor moves the previous area position of the div?
I have tried:
#test {
border: 1px solid black;
width: 100px;
height: 150px;
}
#test:hover {
transform: translate(300px, 0px);
transition: all 3s ease;
}
<div id="test">
Hover me but the cursor always moves in the previous position of the div's area
</div>
As you can see, the div always translates when the cursor moves in the previous position of the div. But I want the translation stopped even if the cursor moves in the previous area. Thanks
Illustration:
4
Answers
Try like this :
Is the onMouseOver function did answer the question?
I’m sorry, but i hope it could help you in some ways.
Here how:
Make a wrapper, then use
:hover
on it instead (note that it isinline-block
):As your illustration shows, we can use some box that stays in the previous position. That box may be an actual element (like the
#wrapper
in InSync’s answer), or a pseudo-element.The initial problem with using a pseudo-element is: Since it is a child, it will naturally follow its translating parent.
To make it "stay in place", we need the pseudo-element to e.g. translate into the opposite direction:
Notice how the pseudo-element is placed in front of other content because of
position: absolute
. This obstructs the actual content e.g. from receiving pointer events.But we can use the
z-index
property to place it behind other content.By declaring
z-index: -1
on the pseudo-element, it will be placed behind. Unfortunately, it will also be placed behind any ancestor in the same stacking context:The CSS Transforms Module Level 1 specification reads:
Simply put: Luckily the pseudo-element is where it is supposed to be when needed; when
#test
is translating.Alternatively, we could establish a new stacking context to always exist by declaring
z-index: 0
on#test
.Note: The pseudo-element is still placed in front of
#test
‘s box, so it will still obstruct#test
‘s background. Since the pseudo-element will be transparent, this shouldn’t be an issue.If you want the transition to also apply when not hovering, simply declare it on
#test
(instead of on#test:hover
):Note: Don’t forget to make the pseudo-element also transition when not hovering!