如何垂直居中响应剪裁图像?

时间:2017-01-16 01:20:41

标签: javascript html css clipping image-clipping

我正在尝试垂直居中剪裁的图像。图像是响应的。在移动设备上,图像是全尺寸的,看起来很好。但是,当浏览器对笔记本电脑进行扩展时,图像的整个下半部分都会被裁掉,并且顶部没有任何东西被裁剪掉。

我尝试使用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
    }
});

1 个答案:

答案 0 :(得分: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