Search code examples
htmlcssparallax

How to set a CSS background to scroll slowly?


I have a single page design currently with background images set in CSS, with background-position: fixed; This works well, but I'd like the background images to scroll, rather than being fixed - but scroll slightly, not at the same speed as the content. (Parallax)

I understand that there are several parallax solutions available, but are any of them suitable for my design without drastically changing it?


Solution

  • Suppose you are usng jquery.

    Try this plugin:

    (function($) {
    
                    $.fn.parallax = function(options) {
    
                        var windowHeight = $(window).height();
    
                        // Establish default settings
                        var settings = $.extend({
                            speed        : 0.15
                        }, options);
    
                        // Iterate over each object in collection
                        return this.each( function() {
    
                            // Save a reference to the element
                            var $this = $(this);
    
                            // Set up Scroll Handler
                            $(document).scroll(function(){
    
                                    var scrollTop = $(window).scrollTop();
                                        var offset = $this.offset().top;
                                        var height = $this.outerHeight();
    
                            // Check if above or below viewport
                            if (offset + height <= scrollTop || offset >= scrollTop + windowHeight) {
                                return;
                            }
    
                            var yBgPosition = Math.round((offset - scrollTop) * settings.speed);
    
                                 // Apply the Y Background Position to Set the Parallax Effect
                                $this.css('background-position', 'center ' + yBgPosition + 'px');
    
                            });
                        });
                    }
                }(jQuery));
    
                $('.bg-1,.bg-3').parallax({
                    speed : 0.15
                });
    
                $('.bg-2,.bg-4').parallax({
                    speed : 0.25
                });
    
                $('.bg-5, .bg-7').parallax({
                    speed : 0.35
                });
                $('.bg-6, .bg-8').parallax({
                    speed : 0.15
                });
                $('.bg-9, .bg-11').parallax({
                    speed : 0.25
                });
                $('.bg-10').parallax({
                    speed : 0.35
                });
            }
    

    Change your selectors (e.g. '.bg_1') according to your markup