我正在尝试垂直居中剪辑的图像。图像是响应式的。在移动设备上,图像是全尺寸的,看起来不错。但是,当浏览器被扩展时,比如笔记本电脑,图像的整个下半部分都被裁剪掉,顶部没有任何东西被裁剪。
我尝试在CSS中玩弄数字。如果图像宽度约为 800px,则显示效果更好,但所有剪辑仍在底部完成。
任何使图像垂直居中并保持响应的想法将不胜感激。谢谢!
.HTML:
<div class="image-wrap" id="wrapper">
<img src="cropped-img.jpg" alt="Oceanside Pier">
</div>
.CSS:
.image-wrap {
max-height: 450px;
overflow: hidden;
max-width: 100%px;
-webkit-transition: max-width .5s ease-out; /* Saf3.2+, Chrome */
-moz-transition: max-width .5s ease-out; /* FF4+ */
-ms-transition: max-width .5s ease-out; /* IE10? */
-o-transition: max-width .5s ease-out; /* Opera 10.5+ */
transition: max-width .5s ease-out;
}
.image-wrap img {
width: 100%;
-webkit-transition: margin-top .5s ease-out; /* Saf3.2+, Chrome */
-moz-transition: margin-top .5s ease-out; /* FF4+ */
-ms-transition: margin-top .5s ease-out; /* IE10? */
-o-transition: margin-top .5s ease-out; /* Opera 10.5+ */
transition: margin-top .5s ease-out;
}
@media only screen and (min-width: 100%px) {
.image-wrap { max-width: 100%; }
}
JavaScript:
$(document).ready(function() {
var imageHeight, wrapperHeight, overlap, container = $('.image-wrap');
function centerImage() {
imageHeight = container.find('img').height();
wrapperHeight = container.height();
overlap = (wrapperHeight - imageHeight) / 2;
container.find('img').css('margin-top', overlap);
}
$(window).on("load resize", centerImage);
var el = document.getElementById('wrapper');
if (el.addEventListener) {
el.addEventListener("webkitTransitionEnd", centerImage, false); // Webkit event
el.addEventListener("transitionend", centerImage, false); // FF event
el.addEventListener("oTransitionEnd", centerImage, false); // Opera event
}
});
如果我正确理解了您想做的事情,请尝试注释您的 js 以使图像居中并使用以下样式
.image-wrap img {
object-fit:cover;//you can also try "contain" here
object-fit:center;
width: 100%;
-webkit-transition: margin-top .5s ease-out; /* Saf3.2+, Chrome */
-moz-transition: margin-top .5s ease-out; /* FF4+ */
-ms-transition: margin-top .5s ease-out; /* IE10? */
-o-transition: margin-top .5s ease-out; /* Opera 10.5+ */
transition: margin-top .5s ease-out;
}
http://caniuse.com/#search=object-fit