Similar to CSS background image to fit width, height should auto-scale in proportion, I want to scale an image to a fixed width, with an unlimited height.
Unlike that question though, this is for a <div>
, not the <body>
, which seems to introduce issues.
I've tried using the CSS3 property background-size: cover
, but that shows 2 images like this (correct width but not tall enough):
I've also tried using background-size: contain
, but that shows like this (not wide enough, therefore not tall enough):
I'm trying to get the images to look like this:
Here's a JSFiddle I've setup.
How can I get the <div>
's to be 171px
wide, but also auto-scale the height?
The dimensions of the images are not known. The images must come in the format <div style="background-image: url('base64')">
, (not <img src="base64">
- due to a restriction on the CLI program it is forwarded to) but I can modify any other HTML or CSS.
I have also tried using JavaScript to calculate what the height should be. That works good, but the <div>
's are not actually resized at the end:
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++)
{
var img = new Image();
img.src = divs[i].style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2');
var ratio = img.width / 171;
var height = Math.floor(img.height / ratio);
alert(height);
divs[i].height = height;
}
Here's an updated JSFiddle with the JavaScript.