我目前正在开发一个网站,其中包含大量具有特定比例的图像。我试图让一个 div 在保持其纵横比的同时水平和垂直调整大小,在以下两个网站上可以看到类似的效果:
http://www.bureaucollective.ch/
如您所见,图像在保持纵横比不变的同时水平和垂直调整了大小。这些图像也在窗口内垂直居中,这是我要包含在我正在开发的网站中的内容。
目前我的代码如下:
body, html {
height: 100%;
background: #f0f0f0;
}
#content {
background: #FFF;
margin: 0 auto;
min-height: 100%;
width: 80%;
}
div.stretchy-wrapper {
width: 80%;
margin: 0 auto;
padding-bottom: 56.25%; /* 16:9 */
position: relative;
background: #000;
}
div.stretchy-wrapper > div {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
}
<body>
<div id="content">
<div class="stretchy-wrapper">
<div></div>
</div>
</div>
</body>
最佳答案
这是一个与http://www.yesstudio.co.uk/ 非常相似的更新.
HTML
<div id="content">
<div class="stretchy-wrapper">
<div></div>
</div>
</div>
CSS
<style>
body, html {
height: 100%;
background: #f0f0f0;
overflow:hidden
}
#content {
background: #FFF;
margin: 0 auto;
}
div.stretchy-wrapper {
margin: 0 auto;
position: relative;
background: #000;
width:100%;
height:100%
}
div.stretchy-wrapper > div {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
}
</style>
js
<script>
function resize(){
var winwidth, winheight, conwidth, conheight, imgheight, imgwidth, top, left;
winwidth = $(window).width();
winheight = $(window).height();
conwidth = winwidth - 260;
if(conwidth < 493){ conwidth = 493; }
conheight = winheight - 95;
conratio = conwidth/conheight;
imgwidth = 1200;
imgheight = 800;
imgratio = 1200/800;
if(conratio < imgratio){
width = conwidth;
height = conwidth / imgratio;
} else {
height = conheight;
width = conheight * imgratio;
}
if(width > imgwidth || height > imgheight){
width = imgwidth;
height = imgheight;
}
top = (winheight/2) - (height/2);
left = (winwidth/2) - (width/2);
arrowheight = Math.round((winheight - height) / 2);
if(left < 130){left = 130; }
$("#content").css("top",top+"px").css("left",left+"px");
$("#content").css("height",height+"px").css("width",width+"px");
}
$(window).resize(resize);
$(document).ready(function(e) {
resize();
});
</script>
最后这是一个有效的 Demo :) 享受
关于html - 具有内在比率的响应式 DIV,可水平和垂直缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16855771/