Twitter Bootstrap modal opening/closing causes fixed header to jump
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!
Bootstrap adds class="modal-open"
and padding-right: 15px;
to body
when the modal is shown. To remove the right shift and keep the scroll bar add this to your css:
body.modal-open {
overflow: inherit;
padding-right: 0 !important;
}
Tried in bootstrap 3.3.4
When the modal opens, the "modal-open" class is added to the HTML <body>
element which hides overflow. You can change this by over-writing the "modal-open" class with overflow: inherit
. This will keep the scrollbar in view, just as it is when the modal is closed. Keep in mind that this will change the overflow option whenever any modal is opened on the page. Hope this helps. Good luck!
As you usually put Bootstrap navbar
as a direct child of the body
container:
<body>
<nav class="navbar navbar-fixed-top">...</nav>
</body>
You can use the body
padding-right
value, calculated in the Bootstrap core code to prevent it from "jumping" when opening a modal window, to fix the navbar
issue as well . A pure CSS solution is below:
.navbar-fixed-top {
padding-right: inherit;
}
Easy as that.