1

If you hover over the box in my example, then the color of the small box changes slowly from red to yellow. But if you stop hovering then it immediately jumps back to red.

.container { position: relative; background: black; width: 200px; height: 200px; }
.subcontainer { position: absolute; bottom: 10px; width: 100%; height: 20px; background: red; animation-duration: 2s; }

.container:hover .subcontainer { background: yellow; animation-duration: 2s; animation-name: example; }

@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}
<div class="container">
  <div class="subcontainer">

  </div>
</div>

How can I prevent this instant color change? I tried to add animation-duration: 2s; to .subcontainer as well, but it does not work.

1 Answer 1

3

You need a transition defined in the .subcontainer instead of an animation

.container { 
    position: relative; 
    background: black; 
    width: 200px; height: 200px; }

.subcontainer { 
    position: absolute; 
    bottom: 10px; width: 100%; height: 20px; 
    background: red; 
    transition: background 2s 0s }

.container:hover .subcontainer { background: yellow;  }
<div class="container">
  <div class="subcontainer">

  </div>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Why do you add the background to transition though? I noticed it does also work if you remove it.
if you remove the property then the transition will occur on every property you change on hover

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.