0

我试图垂直居中被剪裁的图像。图像是响应式的。在移动设备上,图像是全尺寸的,看起来不错。但是,当浏览器扩展为笔记本电脑时,图像的整个下半部分被裁剪掉,顶部没有任何内容被裁剪。

我试着玩弄 CSS 中的数字。如果图像的宽度约为 800 像素,它会显示得更好,但仍然会在底部完成所有剪切。

任何能使图像垂直居中并保持响应的想法将不胜感激。谢谢!

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
    }
});
4

1 回答 1

0

如果我做对了你想做的事,请尝试评论你的 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

于 2017-01-16T01:34:10.467 回答