Reputation: 3765
Covering a page with image in CSS seems troublesome. My prequisities are:
1) Image always fully visible 2) Cover as much as possible 3) Keep aspect ratio 4) Desktop - mobile responsiveness
Any feasible solutions? I've tried the infamous flex-box, basic css, jquery and background-size: contain, but I seem to be missing something.
My goal is to fill the whole page with an image, keep the aspect ratio always correct and fill as much as I can from the screen space (rotation is okay on mobile devices).
.className {
max-width: 100%;
max-height: 100%;
bottom: 0;
left: 0;
margin: auto;
overflow: auto;
position: fixed;
right: 0;
top: 0;
}
EDIT: http://jsfiddle.net/xem36f7h/4/ is behaving correctly besides some weird scrollign with iphone 5S
Upvotes: 0
Views: 205
Reputation: 35
I wrote this. It seem to work on every device I tested its. Just change YOURIMAGESOURCE, YOURIMAGEX, YOURIMAGEY.
HTML
<div id="resizediv">
<img src="YOURIMAGESOURCE">
</div>
CSS
#resizediv {
margin: auto;
left: 0;
right:0;
}
#resizediv img {
width: 100%;
height: 100%;
}
JQUERY
<script>
function resizebyratio(x, y) {
var screenw = window.innerWidth;
var screenh = window.innerHeight;
var screenratio = screenw / screenh;
var divratio = x / y;
if (divratio <= 1) {
var divwidth = screenh * x / y;
$("#resizediv").css({"height":screenh+"px", "width":divwidth+"px"});
}
else if (1 < divratio && divratio <= screenratio) {
var divwidth = screenh * x / y;
$("#resizediv").css({"height":screenh+"px", "width":divwidth+"px"});
}
else {
var divheight = screenw * y / x;
var mtop = (screenh - divheight) / 2;
$("#resizediv").css({"width":screenw+"px", "height":divheight+"px", "margin-top":mtop+"px"});
};
};
$(document).ready(resizebyratio(YOURIMAGEX, YOURIMAGEY));
</script>
Upvotes: 1
Reputation: 2823
I'm not sure how many images are on the page together, but this will find all of images the and resize by height.
Update: This will now maintain aspect ratio and maximize size without going off page.
JS:
function resize() {
var img = document.getElementsByTagName('img');
var w = window.innerWidth;
var h = window.innerHeight;
console.log(w);
console.log(h);
for (i = 0; i < img.length; i++) {
var ratio = (img[i].clientHeight / img[i].clientWidth);
if (img[i].clientHeight > h && img[i].clientWidth < w) {
img[i].style.height = h + "px";
img[i].style.width = (h / ratio) + "px";
}
if (img[i].clientHeight <= h && img[i].clientWidth < w && ratio > 1) {
img[i].style.height = h + "px";
img[i].style.width = (h / ratio) + "px";
}
if (img[i].clientWidth >= w) {
img[i].style.width = w + "px";
}
if (img[i].clientHeight < h && img[i].clientWidth <= w && ratio < 1) {
img[i].style.width = w + "px";
}
}
}
resize();
window.onresize = resize;
CSS:
img {
max-width:100%;
max-height:100%;
display: block;
margin: 5px auto
}
http://jsfiddle.net/hopkins_matt/k7t26sw5/
Upvotes: 0
Reputation:
Have you tried background-size: cover
?
http://jsbin.com/limobop/1/edit?css,output
Upvotes: 0