Vikas Kumar Vikas Kumar - 5 months ago 7
CSS Question

What is the difference between applying CSS transition property in hover rather than in its normal state?

I'm learning CSS3. Now, what I've seen in w3schools website is that:

CSS

#ID{
transition: transform 3s;
}
#ID:hover{
transform: rotateX(20deg);
}


And what I did is this:

CSS:

#ID:hover{
transform: rotateX(20deg);
transition: transform 3s;
}


Both are working. So, the question is: Can I put both transition and any transformation property in same selector? Or is it not the right way?

Answer

SHORT ANSWER:

If you define your transition property in element:hover, it will only get applied in that state.


EXPLANATION:

Whichever CSS properties you define in element:hover will only be applied when the element is in the hover state, whereas whichever CSS properties you define in your element will be applied in both states.


Transition property declared in normal state:

See how the transition always runs when the element's state is changed. When you stop hovering the element it will still make the transition back to its normal state.

CODE SNIPPET:

#ID {
  width: 100px;
  height: 100px;
  margin: 0 auto;
  background-color: royalblue;
  transition: transform 1s;
}
#ID:hover {
  transform: rotateX(60deg);
}
<div id="ID"></div>


Transition property declared in hovered state:

See how the transition breaks when you stop hovering the element and it jumps to its normal state immediately.

CODE SNIPPET:

#ID {
  width: 100px;
  height: 100px;
  margin: 0 auto;
  background-color: royalblue;
}
#ID:hover {
  transition: transform 1s;
  transform: rotateX(60deg);
}
<div id="ID"></div>