Andy
Andy

Reputation: 1432

fadein background color on hover using CSS

This pretty simple JSFiddle (http://jsfiddle.net/AndyMP/sj2Kn/) changes the background colour of a block on 'hover', but how do I get it to fadein/fadeout?

.block {
    width: 200px;
    height: 200px;
    border: 1px solid #333;
}
.block:hover {
    background-color: #333;
}

Upvotes: 1

Views: 247

Answers (3)

SW4
SW4

Reputation: 71150

Demo Fiddle

Add transition:background 200ms ease-in; to .block

.block {
    width: 200px;
    height: 200px;
    border: 1px solid #333;
    transition:background 200ms ease-in;
}

Where 200ms is the amount of time you wish the fade to take.

The CSS property transition defines you want an animation to take place, the three following parts are the specific property you want to transition (can be set to all), the speed, and the animation timing function.

More on CSS transitions from MDN

CSS transitions, which are part of the CSS3 set of specifications, provide a way to control animation speed when changing CSS properties. Instead of having property changes take effect immediately, you can cause the changes in a property to take place over a period of time. For example, if you change the color of an element from white to black, usually the change is instantaneous. With CSS transitions enabled, changes occur at time intervals that follow an acceleration curve, all of which can be customized.

Upvotes: 3

Mr. Alien
Mr. Alien

Reputation: 157314

You need to use transition property

.block {
    width: 200px;
    height: 200px;
    border: 1px solid #333;
    -webkit-transition: background .5s; /* For webkits */
    transition: background .5s;
}

Demo

The property is simple, the first parameter you pass is the property you want to animate, so say you want to animate the height you can pass the height or you can use all as the value if you want to transit all the properties which are transitional, and the next parameter is the time we set for the transition, you can set as 1s, 2s and so on where S stands for seconds.


It's worth noting that the property am using is a short hand property for the following properties

transition-delay: 0s
transition-duration: 0s
transition-property: background
transition-timing-function: ease

Where in the above example we are using the transition-property and transition-duration, default values are used for other properties.

Upvotes: 3

Orahmax
Orahmax

Reputation: 2341

JSFIDDLE

  .block {
        width: 200px;
        height: 200px;
        border: 1px solid #333;
        transition: all 0.25s ease;
        -moz-transition: all 0.25s ease;;
        -webkit-transition: all 0.25s ease;
    }
    .block:hover {
        background-color: #333;
        transition: all 0.25s ease;
        -moz-transition: all 0.25s ease;;
        -webkit-transition: all 0.25s ease;
    }

Upvotes: 1

Related Questions