Oscar Godson
Oscar Godson

Reputation: 32716

Background attachment fixed but full size image

I tried the solutions here: CSS background-size: cover + background-attachment: fixed clipping background images

and some other places but they don't quite work. The JS solution at the top:

$(window).scroll(function() {
  var scrolledY = $(window).scrollTop();
  $('#container').css('background-position', 'left ' + ((scrolledY)) + 'px');
});

Is extremely jittery because its repositioning constantly. The other solution (the responsive_calc one) doesn't work in that I want it centered. The solution always has it left aligned.

I basically want a background-size: cover; but fixed attachment.

JS based solution is fine as long as it doesn't calculate as you scroll.

You can see a demo of the issue here: https://codepen.io/oscargodson/full/abZbZeE

It should look like this

enter image description here

But I get this:

enter image description here

Upvotes: 2

Views: 385

Answers (1)

Temani Afif
Temani Afif

Reputation: 272744

Using an image tag it's doable considering object-fict and position:fixed

* {
  box-sizing: border-box;
}
body {
  margin: 0;
}

.home-panel {
  display: grid;
  grid-template-columns: 50% 50%;
  align-items: center;
  height: 100vh;
}

.home-panel-media {
  height: 100vh;
  clip-path: inset(0); /* to clip the image to this div */
}

.home-panel-media img {
  height: 100vh;
  width: 50vw;
  position: fixed;
  top: 0;
  right: 0;
  object-fit: cover;
  object-position: top center;
}
<div id="wrapper">
  <div class="home-panels-wrapper">
    <div class="home-panel home-panel-1">
      <div class="home-panel-content">
        <h1>Hello World</h1>
        <p>
          Lorem ipsum dolar gamet
        </p>
        <p>
      </div>
      <div class="home-panel-media">
        <img src="https://i.pinimg.com/originals/a1/1e/2a/a11e2a9d5803e4dc2c034819ce12a16e.jpg">
      </div>
    </div>
    <div class="home-panel home-panel-2">
      <div class="home-panel-content">
        <h1>Hello World</h1>
        <p>
          Lorem ipsum dolar gamet
        </p>
        <p>
      </div>
      <div class="home-panel-media">
        <img src="https://images.squarespace-cdn.com/content/v1/56e05d74746fb93dcd805e8b/1553109528895-RYRDJLVNN61UDN65S59U/ke17ZwdGBToddI8pDm48kDmiacAi515_OfcChA6MRIQUqsxRUqqbr1mOJYKfIPR7LoDQ9mXPOjoJoqy81S2I8PaoYXhp6HxIwZIk7-Mi3Tsic-L2IOPH3Dwrhl-Ne3Z23Oc3-AlX22j3PUzoYuTVI2MKzQWw7jmw4KYJnTQU-9E_twk1mUNduAk0T15_nZ7z/Tulsa-Headshot-Photographer_9639a.jpg?format=1500w">
      </div>
    </div>
  </div>
</div>

Upvotes: 2

Related Questions