Search code examples
htmlcssimagetransformscale

CSS transform: scale not working as wanted


I want to have text directly below an image that I am scaling with transform: scale(0.50, 0.50);

The issue is that the height and width of the bounding box of the image don't scale with the image. There was another post from which I got this image example of scaled image, but it is not the answer I'm looking for. How can I make the borders of the larger, pre-scaled image match the smaller, new scale of the image? My code is as follows:

.content #imagediv {  
    background-color: blue;  
}  
.content #imagediv img {  
    transform: scale(0.50, 0.50);  
    transform-origin: top left;  
    display: inline-block;  
}

This looks like this


Solution

  • I think you'll have to change the image size using another method. I don't think transfrom: scale will work in this case. Why not just set the image width and let the height be dynamic?? The text will sit right under the image at that point. You could also use js to change the width of the image to 50% of its original if you need it to be 50%.

    var img = document.getElementById('image'); 
    //or however you get a handle to the IMG
    var width = img.clientWidth;
    img.style.width = (width / 2) + 'px';
    .content #imagediv {  
        background-color: blue;
        line-height:0; //used to get rid of extra space after the image.
    }  
    .content #imagediv img {  
        width:400px; //changes to 200px with js. Even if this is not set it will still get set to 200px because the js is calulating based off the image size.
    }
    <div class="content">
        <div id="imagediv">
            <img id="image" src="https://via.placeholder.com/400x400" />
        </div>
        <span>Random Text I want right below the image</span>
    </div>