Reputation: 61
I've got a set of divs and I want each of them to have different background color and while on hover to transition to a background image of chosen url. I have so far managed to find code for smooth color -> image transition but that requires an actual img code in HTML and I need those divs as I will be putting text in them.
Is there any chance to have a smooth 0.5s or less transition from background color to background image with CSS?
Upvotes: 5
Views: 10952
Reputation: 103760
You can't animate the background
property from solid color to image with CSS3 transitions.
To achieve the desired behaviour, you will need to fade in/out a layer with your solid background color. You may use a pseudo element to minimize markup for the solid color latyer layer.
Here is an example :
div {
position: relative;
width: 250px;
height: 250px;
background: url(https://picsum.photos/250);
}
div:after {
content: '';
position: absolute;
left: 0; top: 0;
width: 100%; height: 100%;
background: gold;
opacity: 1;
transition: opacity .5s;
}
div:hover:after {
opacity: 0;
}
<div></div>
Upvotes: 7
Reputation: 2984
This should get you started = FIDDLE.
You could also use JS, but it isn't necessary.
CSS
.changeme {
margin: 10px auto;
width: 200px;
height: 200px;
background-color: red;
text-align: center;
line-height: 200px;
color: blue;
font-size: 30px;
}
.changeme:hover {
background-color: transparent;
background: url('http://i.imgur.com/DgYUsKY.jpg?1');
}
.changeme2 {
margin: 10px auto;
width: 200px;
height: 200px;
background-color: blue;
text-align: center;
line-height: 200px;
color: white;
font-size: 30px;
}
.changeme2:hover {
background-color: transparent;
background: url('http://i.imgur.com/BF7aTQR.jpg');
}
Upvotes: 1