简体   繁体   中英

make image height be the 1/4 of the window's height

I try to make an image's height to always be the 1/4 of the window's height, based on responsive design and fluid images

The image is a random image picked up by the database, so I dont know if its gonna be elongated or not.

This is what I got untill now

//after the path of the image is randomly collected with websockets
elem = document.createElement("img");
 elem.id="frontimage";
 elem.setAttribute("height", window.innerWidth/4+'px');

document.getElementById("icon").appendChild(elem);  

//this is triggered after window.onresize (see below)-in case the browser window is scaled
function img_adjust( img ) {
 var beholdItsTheNewHeight = window.innerWidth/4;
img.style.height  = beholdItsTheNewHeight  + 'px';
}

window.onresize = function() {
img_adjust( document.getElementById('frontimage') );
}


<div id="icon"  ></div>

(based on the anser by migf1, from here , sorry its Greek)

And that's it. Works fine , if you just open a browser and the browser expands to the whole screen.

Problems

-I simply cannot align the image to the center of its container. I tried margin, padding, float, position:absolute . Nothing works

-If I start scaling the browser's window (simply dragging one corner) the image's height does not "follow". Resizes, but not actually in 1/4 of screen's height.

-If I open a browser and it's not expanding to the whole screen, the image's height not scale to the 1/4 of screen's height.

Any advise?

Thanks in advance

You can use css property #icon{ text-align: center;} on the container DIV to center the image horizontally within the DIV. Look at: http://jsfiddle.net/2vxmX/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM