Search code examples
csscss-transitions

CSS 3 slide-in from left transition


Is there a cross-browser solution to produce a slide-in transition with CSS only, no javascript? Below is an example of the HTML content:

<div>
    <img id="slide" src="http://.../img.jpg />
</div>

Solution

  • You can use CSS3 transitions or maybe CSS3 animations to slide in an element.

    For browser support: http://caniuse.com/

    I made two quick examples just to show you what I mean.

    CSS transition (on hover)

    Demo One

    Relevant Code

    .wrapper:hover #slide {
        transition: 1s;
        left: 0;
    }
    

    In this case, I'm just transitioning the position from left: -100px; to 0; with a 1s. duration. It's also possible to move the element using transform: translate();

    CSS animation

    Demo Two

    #slide {
        position: absolute;
        left: -100px;
        width: 100px;
        height: 100px;
        background: blue;
        -webkit-animation: slide 0.5s forwards;
        -webkit-animation-delay: 2s;
        animation: slide 0.5s forwards;
        animation-delay: 2s;
    }
    
    @-webkit-keyframes slide {
        100% { left: 0; }
    }
    
    @keyframes slide {
        100% { left: 0; }
    }
    

    Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case, I've set animation-fill-mode to forwards, which will persist the end state, keeping the div visible when the animation ends.

    Like I said, two quick examples to show you how it could be done.

    EDIT: For details regarding CSS Animations and Transitions see:

    Animations

    https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations

    Transitions

    https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions