Marrrc Marrrc - 3 months ago 18
CSS Question

Bootstrap parallax

I'm trying to add a parallax effect to the bootstrap jumbotron background image. I got it working except for this obnoxious effect that occurs on smaller screen sizes. Whenever the width of the image exceeds that of the screen the image scales down during the scroll which ruins the parallax effect.

Removing background-size, which is set to cover, fixes the unwanted scaling but then adds white spaces on larger screens.

CSS

.jumbotron-bg {
background: url("http://res.cloudinary.com/mrcloud/image/upload/q_100/v1472550908/slide-01_vksled.jpg") no-repeat center center, rgba(112, 152, 255, 0.5);
position: fixed;
width: 100%;
height: 550px; /*same height as jumbotron */
top: 0;
left: 0;
z-index: -999;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-blend-mode: soft-light;
-webkit-background-blend-mode: soft-lightsoft-light;
}


JS

var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
var scrolled = $(window).scrollTop();
$('.jumbotron-bg').css('height', (jumboHeight-scrolled) + 'px');
}
$(window).scroll(function(e){
parallax();
});


Codepen example: http://codepen.io/MarcRuemekorf/pen/KgProm

Advice would be greatly appreciated.

Answer

If removing the background-size:cover fixes your issue on smaller screens but gives you the desired results on larger screen use media queries to only apply the background-size on medium/larger screens.

.jumbotron-bg {
  background: url("http://res.cloudinary.com/mrcloud/image/upload/q_100/v1472550908/slide-01_vksled.jpg") no-repeat center center, rgba(112, 152, 255, 0.5);
  position: fixed;
  width: 100%;
  height: 550px;
  /*same height as jumbotron */
  top: 0;
  left: 0;
  z-index: -999;
  background-blend-mode: soft-light;
  -webkit-background-blend-mode: soft-lightsoft-light;
}

/* Medium */
@media(min-width:992px) and (max-width:1199px) {
  .jumbotron-bg {
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
  }
}

/* Large */
@media(min-width:1200px) {
  .jumbotron-bg {
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
  }
}
Comments