Search code examples
cssbackground-imagescale

Scaling a background image relative to its own size?


I have a div in which I have set the background to a certain image. Let's say for example that the div is 300x300, and that the original background image size is 200x200.

I want to scale the background image by a certain percentage relative to itself. For example, if I were to scale by 200%, I want the background image to now be 400x400 pixels and be slightly cut off. But the only css property I've been able to find is the background-size property, which scales with a percentage relative to the parent div (eg. with 200% scale, the background image would become 600x600).

Is there any way to achieve scaling relative to the background image itself?


Solution

  • So I actually found a way to do this using purely css. The issue I was having of course, is that background-size scales relative to the div we're setting the background of, as opposed to the image size itself.

    The workaround is that we can wrap the div in a parent div with the width and height that we want, then set the inner div's width and height equal to that of the background image we're using. This way we can scale the inner div according to the background's size, since they are equal in size, then crop off the correct amount by setting the parent to overflow: hidden.

    *The only catch is that we must use server-side rendering to set the inner div's width and height to the image's width and height without using javascript.

    For example:

    <div style="width: 300px; height: 300px; overflow: hidden;">
        <div style="width:{{bgimgwidth}}; height:{{bgimgheight}}; background: url('{{url}}'); background-size: 200%;">
        </div>
    </div>