CSS : Image hover transition not working with display none / display:block and image swap

守給你的承諾、 提交于 2019-12-06 15:03:06

Assuming all the images are the same height, you could set a fixed height on the parent element and then relatively position it.

.effect {
    position:relative;
    height:94px;
}

Absolutely positioning the img elements and remove display:none.

div.effect img.image {
    opacity: 1;
    -webkit-transition: opacity 0.5s ease-in-out;
    -moz-transition: opacity 0.5s ease-in-out;
    -o-transition: opacity 0.5s ease-in-out;
    -ms-transition: opacity 0.5s ease-in-out;
    transition: opacity 0.5s ease-in-out;
    position:absolute;
}

The reason this works is because the child img elements are absolutely positioned relative to the parents, effectively positioning both images on top of each other. You no longer need to change the display of the element, thus allowing the transition to take place.

UPDATED EXAMPLE HERE


Alternatively, if the images aren't all the same height, omit the height, but still relatively position the parent element. As opposed to absolutely positioning both images, just position one and it will still work.

ALTERNATIVE EXAMPLE HERE

div.effect img.hover {
    opacity: 0;
    position:absolute;
    top:0;
}

It's also worth noting that you don't need to include the transition properties on all the elements if they have the same values. Having it on the div.effect img.image will suffice.

Take a look at this example.

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