user3033162
user3033162

Reputation: 135

why this css transition doesn't work

.box {
  width: 150px;
  height: 150px;
  background: red;
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  -webkit-transition: background-color 0.3 ease-out;
  -moz-transition: background-color 0.3s ease-out;
  -o-transition: background-color 0.3s ease-out;
  transition: background-color 0.3s ease-out;
      opacity:0.2;
}

.box:hover {
  cursor: pointer;
  opacity:1;
}

I try to do a transition with opacity, it doesn't work, but it can work if I do the background change effect.

demo http://jsfiddle.net/rsg4e/

Upvotes: 1

Views: 4655

Answers (4)

Deryck
Deryck

Reputation: 7668

You were on the right track - just went the wrong way.

Fixed your fiddle

What you wanted was the background-color to change opacity, not the full element and whatever might be inside of it. All you need to do is set the backgrounds to rgba() values and you're set.

.box {

  background-color: rgba(255,0,0,0.2);

}
.box:hover {

  background-color: rgba(255,0,0,1);

}

Of course - if you ACTUALLY want everything inside of it to change opacity as well, then go with one of the other answers - they hit it on the head.

Upvotes: 3

agconti
agconti

Reputation: 18123

There's not a background-color property to transition because you've specified it as background. so naturally the transition wont work.

Change it to :

-webkit-transition: background 0.3 ease-out;
  -moz-transition: background 0.3s ease-out;
  -o-transition: background 0.3s ease-out;
  transition: background 0.3s ease-out;

or

-webkit-transition: all 0.3 ease-out;
  -moz-transition: all 0.3s ease-out;
  -o-transition: all 0.3s ease-out;
  transition: all 0.3s ease-out;

and your hover state to

.box:hover { background: /*younewcolor*/;}

and everything should should work fine.

Upvotes: 1

codingrose
codingrose

Reputation: 15709

Write

transition: opacity 0.3 ease-out;

Instead of

transition: background-color 0.3 ease-out;

Because on hover you are changing opacity not background.

.box {
  width: 150px;
  height: 150px;
  background: red;
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  -webkit-transition: opacity 0.3 ease-out;
  -moz-transition: opacity 0.3s ease-out;
  -o-transition: opacity 0.3s ease-out;
  transition: opacity 0.3s ease-out;
      opacity:0.2;
}

DEMO

Upvotes: 1

Dan
Dan

Reputation: 8844

You're setting a transition on the background-color, when you should be calling it on the opacity i.e:

-webkit-transition: opacity 0.3s ease-out;

Upvotes: 2

Related Questions