Search code examples
cssoverflowcss-transformsbackground-size

How to overflow background cover to be visibile when using scale transform to make the div smaller?


  1. I have an absolute div (needs to be absolute).
  2. The absolute div has a background-image with the background-size set to cover (size cover necessary)
  3. I'm using a css transform to scale the div upon hover to a value less than 1, for example, scale(0.7)

Issue: I want the cover background-image to overflow beyond the div when it's scaled down.

Why I need it: The image is transparent with different graphics floating around and of the background-size cover so when browsing in a mobile, the transform crops graphics on the edge of the div and scales the div.

CSS solutions only please.

Edit: CSS + js solutions will do.

Example: the outer div is supposed to represent a mobile browser window.

.chivoyage{
    position:absolute; 
    top:0px; 
    right:0px; 
    bottom:0px; 
    left:0px; 
    background-image:url('http://clipart.info/images/ccovers/1495916688repin-image-stars-png-transparent-stars-on-pinterest.png'); 
    background-size:cover;
    background-position:center center;
    transition: all 1s ease-out 0s;
    cursor:pointer;
    }

    .chivoyage:hover{
    transform: scale(0.8);
    }

.window-mobile{
width:150px; height:300px; position:relative; border:1px solid black;
}
<div class="window-mobile"><div class="chivoyage"><div></div>

<div>

Solution

  • Ok after some thought, I arrived at a solution. Basically, background-size: cover logically equals

    1. background-size: 100% auto if the width:height ratio of image is lower than that of container

    2. background-size: auto 100% if the width:height ratio of image is higher than that of container

    So I ended up calculating the ratio using naturalheight and naturalwidth and with an if statement, I get which background-size to apply, thus maintaining the behaviour as cover while being able to work with the values via js to transform background-image.

    On a side note, if you need to work with background-size:contain, just calculate the ratio and do the opposite (1. would be auto 100% and 2. would be 100% auto)