user3790069
user3790069

Reputation:

Where to apply CSS transitions?

Should I apply transition properties to an element or to the element:pseudo-class?

What is preferable,

p {
  color: blue;
  transition: 2s 22ms
}

p:hover {
  color: red
}

or

p {
  color: blue
}

p:hover {
  color: red;
  transition: 2s 22ms
}

?

Upvotes: 1

Views: 76

Answers (3)

hityagi
hityagi

Reputation: 5256

It depends on what you want to achieve.

1st option :

Your text in blue -> mouseover -> transition effect -> your text in red -> mouseout -> transition effect -> your text in blue

2nd option :

Your text in blue -> mouseover -> transition effect -> your text in red -> mouseout -> your text in blue

Choose according to your need.

Upvotes: 2

showdev
showdev

Reputation: 29168

If you apply your transition to :hover, the transition will only happen on mouseover and not on mouseout. Applying the transition to the element rather than its :hover will make the transition happen on both mouseover and mouseout.

Here's a fiddle to help illustrate.

Upvotes: 0

Thom-x
Thom-x

Reputation: 866

If you want the transition to be different depending on the pseudo class you must use the second option. But if you don't care, use the first one.

input {
  color: blue
}

input:hover {
  color: red;
  transition: 2s 22ms
}

input:focus {
  color: red;
  transition: 3s
}

input:active {
  color: red;
  transition: 4s
}

Upvotes: 0

Related Questions