Peter de Leeuw Peter de Leeuw - 6 months ago 34
CSS Question

Twitter Bootstrap modal opening/closing causes fixed header to jump

I am almost done with a simple 2-page website for my registered domain names.
Unfortunately I have one small issue I can't seem to fix: a jumpy header when a Twitter Bootstrap modal opens and closes.
On mobile devices there's no problem. The problem only occurs in larger viewports like desktops and laptops.

How to recreate




  1. Open http://www.domains.cloudlabz.nl/domains in a webbrowser and make sure you get a vertical scrollbar by lowering the viewport height.

  2. Click on one of the blue 'more info' buttons.

  3. Notice the jumping header and disappearing scrollbar once the modal opens.

  4. Close the modal and notice the header jumping back and the scrollbar reappearing.



Check the following image (same result in Opera, Safari, Firefox and Chrome):

Jumping header issue

What I'd like



I'd like the header to stop jumping when opening/closing a modal. The fact the scrollbar disappears is not an issue. Actually, I would like it to stay like that.

Update



I noticed the jumping header only occurs with fixed position elements such as my header (added Bootstrap class navbar-fixed-top). It even occurs on the Bootstrap website itself: http://getbootstrap.com/javascripts. Go to the 'Modals > Optional Sizes' area on a desktop and click one of the buttons. You'll see the right side menu jumping back and forth.

When the modal opens, the class .modal-open is added to the body element (thanks for pointing that out @Pred). It adds a padding of 15px to the right, which is the same width as the scrollbar gutter. This prevents the body from jumping back and forth.

Unfortunately this padding apparently does not apply to fixed elements.

Answer

I seemed to have found a quick fix for my issue. It uses a piece of javascript to add extra style to the header (15px padding-right) to prevent it from jumping. This might not be the best solution but for now it works just fine.

Since there were no issues on viewports smaller than 768px (mobile) this piece of code only adds the extra 15px to larger viewports such as desktops and laptops

<script>

    $(document).ready(function(){

        // Dirty fix for jumping scrollbar when modal opens

        $('#requestModal').on('show.bs.modal', function (e) {
            if ($(window).width() > 768) {
                $(".navbar-default").css("padding-right","15px");
            }
        });

        $('#requestModal').on('hide.bs.modal', function (e) {
            if ($(window).width() > 768) {
                $(".navbar-default").css("padding-right","0px");
            }
        });

    });

</script>

If you know a better solution (preferably CSS3 only), please let me know. Thanks for all the help!