Scale to fit

A simple implementation of a scale-to-fit function that uses a CSS3 transform to resize an element to fit within its container.

by nate

HTML

<div class="container">
    <div id="widget">
    </div>
</div>

CSS

.container {
    border: 10px solid red;
    width: 200px;
}

#widget {
    border: 10px solid blue;
    height: 324px;
    width: 324px;
    -webkit-transform-origin: 0 0;
}

JavaScript

function scaleToFit(element) {
    
    var container = element.parentNode;

    function getWidth(element, borders) {
        var width = 0;
        var style = getComputedStyle(element, null);
        
        borders = borders || false;
        
        if (borders) {
            width += parseInt(style.getPropertyValue('border-left-width'), 10);
            width += parseInt(style.getPropertyValue('border-right-width'), 10);
        }
        
        width += parseInt(style.getPropertyValue('padding-left'), 10);
        width += parseInt(style.getPropertyValue('padding-right'), 10);
    
        width += parseInt(style.getPropertyValue('width'), 10);
        return width;
    }
    
    var ratio = getWidth(container) / getWidth(element, true);
    
    element.style.webkitTransform = 'scale(' + ratio + ')';
}

scaleToFit(document.getElementById('widget'));