Search code examples
javascriptjquerycssmedia-queriesresponsive-design

Adding 'Fade out/Fade in' to Responsive Media Queries


I'm wondering how to add the 'Fade in/Fade out' effects to elements that I make appear or disappear with a responsive web site using CSS3 media queries. I've figured out how to use linear transitions, but would really like to use a fade.


Solution

  • To do this with CSS you will need to use transitions. The only way I can think to fade in/out an element with CSS transitions would be to set the opacity to zero and then animate the opacity back to one, but you can't do this with CSS alone (you would need some JS to time the events properly):

    $(window).on('resize', function () {
        if ($(this).width() <= 480) {
            //do code for less than 480px wide 
            $('#some-element').css('opacity', 0).addClass('transition').css('opacity', 1);
            setTimeout(function () {
                $('#some-element').removeClass('transition');
            }, 500);
        }
    }).trigger('resize');
    

    Where the transition CSS class would have the transition rule set:

    .transition {
        -webkit-transition : opacity 0.5s linear;
           -moz-transition : opacity 0.5s linear;
            -ms-transition : opacity 0.5s linear;
             -o-transition : opacity 0.5s linear;
                transition : opacity 0.5s linear;
    }