Reputation: 785
I have background image that is resizing a little bit when I scroll from the top on mobile devices. And it returns to its size when I scroll to the top again. You can see it here
I tried using
background-attachment: fixed;
besides all the other css code you can see below but it did not work.
css
.bg-1, .bg-2, .bg-3,
.bg-1:after, .bg-2:after, .bg-3:after {
position: fixed;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
z-index: 0;
}
.bg-1 li span, .bg-2 li span, .bg-3 li span {
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
color: transparent;
background-size: cover;
background-position: 50% 50%;
background-repeat: none;
opacity: 1;
z-index: 0;
}
.bg-1 li span { background-image: url(../images/slide-1.jpg); }
.bg-2 li span { background-image: url(../images/slide-3.jpg); }
.bg-3 li span { background-image: url(../images/slide-2.jpg); }
ol,ul {
list-style:none;
}
html
<body>
<ul class="bg-2">
<li><span></span></li>
</ul>
<nav class="navbar">
<div class="container-fluid social-nav">
...
Just to explain, it is a list because if I want to make a slide gallery it works adding more
<li><span></span></li>
But I use slide only in home page.
How can I prevent that resizing?
Upvotes: 3
Views: 3532
Reputation: 6129
If the background-image is resizing on initial scroll, I assume the element with that background must have a dynamic height, generated using either vw/vh in the CSS or JS/jQ script. I ran into this same problem, and I found what I believe to be the correct method in resolving this issue (at least until mobile browsers provide their own workaround).
Using a simple jQuery function, you can store the window's width on page load, and use that to restrict the container's resizing function to viewport sizes wider than the desktop breakpoint (992px+) and narrower viewports so long as the viewport width changes, not just the height. This way, on mobile and tablet devices, when you scroll, there is only a vertical viewport resize, so the resize function is not triggered.
var breakpoint = 991;
var bgHeight = function() {
$('#bg').css('height', $(window).height() + 'px');
}; bgHeight();
var windowWidth = $(window).height();
$(window).on('resize', function() {
if ((($(this).width() <= breakpoint) && ($(this).width() != windowWidth))
|| ($(this).width() > breakpoint)) {
bgHeight();
}
windowWidth = $(window).width();
});
CodePen: https://codepen.io/brandonmcconnell/pen/jayYbB
Upvotes: 2
Reputation: 1109
Take a look at background: fixed no repeat not working on mobile.
I believe the main difference is the z-index=0
, try changing it to -10.
Upvotes: 0