Resize draggable objects background image on resize

1.2k Views Asked by At

This question is related to : Resizable, draggable object in jquery. Possible?

Hello all,

I want to resize the background image of a div on jquery resize. How can I do it?

Thank you

2

There are 2 best solutions below

1
On BEST ANSWER

You can't set the size of a CSS background-image. But maybe this http://www.cssplay.co.uk/layouts/background.html or this will help http://css-tricks.com/how-to-resizeable-background-image/

0
On

Basically this would consist of a resizable container (I'd say div) with a non-static position (that'll happen inevitably if you're making it draggable), a "background" object with position set to absolute and 100% width/height, and a content container (another div) set to position relative. Should do the trick.

<style>
    #resizable { width: 150px; height: 150px; overflow: hidden; }
    #resizable > img.background { width: 100%; height: 100%; position: absolute; top: 0; left: 0;}
    #resizable > div.content { position: relative; padding: 0.5em; color: White; font-weight: bold;}
</style>

<div id="resizable">
    <img src="http://www.path.to/your/image.jpg" class="background">
    <div class="content">
        <p>Content paragraph.</p>
    </div>
</div>

Check out an example: http://jsfiddle.net/wVAT2/

What happens is that setting the image's position to absolute takes it out of the document flow and positions it relative to the first non-statically positioned ancestor (in this case, the containing draggable div). The relative position on the content div is to ensure the proper stack order for the content that follows the image, otherwise the "background" becomes the foreground.

You'd probably have to do some thinking if you wanted to support IE7 with that particular markup to fix the stacking context for jQuery UI's resizing controls, but I'll leave that one to you. Hopefully this will point you in the right direction.

If you want to maintain the background aspect ratio rather than having it stretch as you resize, consider binding a function that resizes the image element on the resizable's resize event.