javascriptcssscrolloverflowbackground-size

If there is a way to do background-size: cover and still be able to scroll around the image


I like background-size: cover with centering because it means your image fills the container element completely. It just lets parts of the image overflow over the sides depending on how it fits in the container.

What I would like to do now is be able to scroll around the image within the background-size: cover constraint. That is, if the image is overflowing on the top and bottom, I can scroll my trackpad up and down and it sort of pans across the image so you can see the rest of it that was covered (sorta like on Google Maps). In this way, you get two benefits:

Wondering if this is possible and how it might be accomplished, either with CSS or plain JavaScript.


Solution

  • I don't think you can achieve this without some heavy javascript or library.

    With html and css, this is the best I can do:

    .cover{
      width: 180px;
      height: 180px;
      display: inline-block;
      overflow: auto;
      overflow: -moz-scrollbars-none; 
      -ms-overflow-style: none;
    }
    
    .cover::-webkit-scrollbar { 
      width: 0 !important;
    }
    
    .cover::after {
      content: '';
      display: block;
      width: 240px;
      height: 360px;
      background-image: url(https://picsum.photos/240/360);
    }
    <div class="cover"></div>
    <span>← Scroll this</span>

    It kinda works if you know the dimensions of the image, but you need to specify the width and height manually which is kinda suck.