Search code examples
htmlcssscale

Scale all images to fit container proportionally


I am building a customization script where a user can upload an image and drag it around a template image to get a desired result. The problem is the template image is over 1000px tall and wide, so I put it inside a container limiting it's height/width.

How do I make it so the uploaded image is scaled exactly the same so when I create the image via PHP I can take the left: and top: CSS values and apply them to the much larger template image and uploaded image?

Current CSS:

#template {
    position: relative;
    padding: 0;
    width: 500px;
    height: 500px;
    z-index: 1;
}
#uploaded {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
}

Solution

  • I'm not quite sure if that is what you are asking for … anyway:

    The CSS3 property background-size: 100% lets you specify that the background image of should fill out the container's size and stretch proportionally. Together with background-repeat: no-repeat it might be what you are looking for:

    #uploaded {
        height: 500px;
        width: 500px;
    
        background-image: url(...);
        background-size: 100%;
        background-repeat: no-repeat;
    }
    

    Demo: http://jsfiddle.net/pu76s/3/