javascript - Scale background image of div to a fixed width; auto-scale height -


similar css background image fit width, height should auto-scale in proportion, want scale image fixed width, unlimited height.

unlike question though, <div>, not <body>, seems introduce issues.

i've tried using css3 property background-size: cover, shows 2 images (correct width not tall enough):

i've tried using background-size: contain, shows (not wide enough, therefore not tall enough):

i'm trying images this:

here's a jsfiddle i've setup.

how can <div>'s 171px wide, auto-scale height?

the dimensions of images not known. images must come in format <div style="background-image: url('base64')">, (not <img src="base64"> - due restriction on cli program forwarded to) can modify other html or css.


i have tried using javascript calculate height should be. works good, <div>'s not resized @ end:

var divs = document.getelementsbytagname('div'); for(var = 0; < 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 javascript.

i've got working js option. needed use divs[i].style.height = height + 'px' instead of divs[i].height = height:

window.onload = function() {     var divs = document.getelementsbytagname('div');     for(var = 0; < 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);         divs[i].style.height = height + 'px';     } } 

here's a working jsfiddle.

i'm still interested know whether possible pure css3 though. you'd think so!


i've further improved code. now, images smaller 171px wide not stretched:

window.onload = function() {     var divs = document.getelementsbytagname('div');     for(var = 0; < divs.length; i++)     {         var img = new image();         img.src = divs[i].style.backgroundimage.replace(/url\((['"])?(.*?)\1\)/gi, '$2');          if(img.width > 170)         {             var ratio = img.width / 171;             var height = math.floor(img.height / ratio);         }          else         {             var height = img.height;             divs[i].style.backgroundsize = 'auto';             divs[i].style.backgroundposition = 'center';         }          divs[i].style.height = height + 'px';     } } 

here's final fiddle.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -