HTML:
<div class="info-panel"></div>
<div class="image">
<img src="http://placehold.it/960x1400">
</div>
CSS:
.image {
height: 100%;
width: auto;
margin-right: 200px;
}
.info-panel {
position: fixed;
width: 200px;
height: 100%;
background-color: red;
right: 0px;
}
我正在尝试动态缩小(从不向上)图像以适应 image-div(不裁剪),它的高度 (100%) 和宽度(设置为自动)是可变的。图像还需要居中(垂直和水平),并在顶部和底部有几个像素的相等填充。
如您在 fiddle 中所见,图像容器旁边有一个信息面板,但我不确定这是否相关。
我的陈述是否有意义?
谢谢,我已经花了太多时间试验这个了! :/
最佳答案
如果我没理解错的话,你想要类似 this 的东西.
如果图像太大,它会按比例缩小,但当它适合窗口时会保持原始大小。换句话说,它永远不会扩大 - 只会缩小。
它是 CSS 和一些 jQuery 的组合:
这个简短的 JS 将图像垂直居中:
function verticallyCenterImage(){
var $img = $('.image img'),
windowHeight = $(window).outerHeight();
if($img.height() < windowHeight){
var delta = windowHeight - $img.height();
$img.css('margin-top', (delta / 2) + 'px');
}else{
$img.attr('style', '');
}
}
这行 CSS 使图像水平居中:
.image {
padding-right: 200px;
text-align: center; /* <- this one */
max-height: 100%;
overflow: hidden;
}
为了保持图像的原始大小,我只是在 .image
类中的 img
上设置最大高度和宽度,如下所示:
.image img {
max-width: 96%;
max-height: 96%;
margin: 2%;
}
您可以根据需要调整大小和边距,但请记住保持它们彼此之间的相关性:)
关于javascript - 使用 JS 在可变大小的 div 中缩放和居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16702167/