Search code examples
csshoverdelaybackground-size

Delay Hover effect on background-size in CSS


I wonder if there is a way to delay the hover effect on background-size that goes from "cover" to "contain"? I have seen transition-delay works on backround-color and other properties but not backround-size. Any help will be appreciated. Thanks!

div{
    display:inline-block;
    width: 100px;
    height: 100px;
    padding:5px;
    margin:10px;
    border:1px solid #ccc;
    background-image: url("https://i.sstatic.net/2OrtT.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: 50% 50%;
    transition: 0s background-size;
    transition-delay:1s;
}
div:hover{
    background-size: contain;
    background-color:red;
}

http://jsfiddle.net/rtku7sqk/

UPDATE Perhaps I should clarify that I want to delay the hover effect to happen but not extend the duration of the animation.

Similar to this... http://dabblet.com/gist/1498443


LATEST UPDATE

I figure out a way to fix this by using a mix of both CSS and javascript.

This way "background-size" works with "contain" and "cover"

$("#tmp").hover(function() {

    /* Mouse enter */
    var thisone = $(this);
    window.mytimeout = setTimeout(function() {
        thisone.addClass("mouseon");
    }, 1000);

}, function() {

    /* Mouse leave */
    clearTimeout(window.mytimeout);
    $(this).removeClass("mouseon");
});

http://jsfiddle.net/rtku7sqk/5/


Solution

  • So, there's only one small little thing with your CSS, otherwise it'll work exactly as you expect.

    You can't transition from non-numerical values

    The values contain and cover for background-size aren't transition-able. Since they're non-numerical, you can't operate a CSS calculation on them.

    If you change that to a numerical value like in the example below, it'll happen exactly how you expect it to:

    Fiddle illustrating this example

    Here are the changes to the CSS:

    div{
        display:inline-block;
        width: 100px;
        height: 100px;
        padding:5px;
        margin:10px;
        border:1px solid #ccc;
        background-image: url("https://i.sstatic.net/2OrtT.jpg");
        background-size: 100%; /* NOT `cover` anymore */
        background-repeat: no-repeat;
        background-position: 50% 50%;
        transition: 0s background-size;
        transition-delay: 1s;
    }
    div:hover{
        background-size: 20%; /* NOT `contain` anymore */
        background-color:red;
    }