transition between background color and background image CSS3

瘦欲@ 提交于 2021-02-05 05:29:11

问题


I've got a set of divs and I want each of them to have different background color and while on hover to transition into 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 url performed through CSS?

If you look at http://loopedmag.com you can see what I want to recreate in code but with the transitioned animation color->image.


回答1:


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 that layer.

DEMO

HTML :

<div class="one"></div>
<div class="two"></div>

CSS :

body,html{
    height:100%;
}

div{
    height:50%;
    width:50%;
    position:relative;
    background-size:cover;
}
.one{
    background: url(http://lorempixel.com/output/fashion-q-c-640-480-3.jpg);
}
.two{
    background: url(http://lorempixel.com/output/people-q-g-640-480-7.jpg);
}
div:after{
    content:'';
    position:absolute;
    left:0; top:0;
    width:100%;
    height:100%;
    background:gold;
    opacity:1;

    -webkit-transition: opacity .5s;
    transition: opacity .5s;
}
div:hover:after{
    opacity:0;
}



回答2:


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');
}


来源:https://stackoverflow.com/questions/23990749/transition-between-background-color-and-background-image-css3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!