保持图像的纵横比,但在达到最大/最小高度时进行裁剪

时间:2015-03-31 22:14:32

标签: css image responsive-design

我试图让这个图像响应它会调整大小并保持所有尺寸的宽高比。然而,在650px以上,它的高度不会增加,但只会裁剪顶部和底部以保持比例而不是伸展。此外,我希望图像高度不会低于200px,只有左右。我希望图像永远是中心。以下是我到目前为止:https://jsfiddle.net/4q83mh41/

<div class="hero">
<img src="http://wpdevserver.x10host.com/wp-content/themes/wp/img/hero1.jpg">
</div>


.hero {
    width: 100%;
    min-height:200px;
    max-height: 650px;
    position: relative;
}
.hero img {
    width: 100%;
    height:auto;
    min-height:200px;
    overflow: hidden;
    max-height: 650px;
    position:aboslute;
}

非常感谢

1 个答案:

答案 0 :(得分:2)

通过添加一些javascript,可以在.hero div内动态调整图像的位置。此外,CSS媒体查询可用于保持图像的宽度正确。

.hero {
  width: 100%;
  overflow: hidden;
  max-height: 650px;
}

.hero img {
  position: relative;
  height: 200px;
  width: auto;
}

@media (min-width:420px) {
  .hero img {
    width: 100%;
    height: auto;
  }
}

javascript只是侦听调整大小事件并调整相对定位图像的topright属性以使其保持居中。请注意,我正在使用JQuery来操作属性。

var heroresize = function() {
  var aspect = 1800./858,
      maxheight = 650,
      minheight = 200,
      width = $(".hero").width();
  if(width < minheight*aspect) {
    $(".hero img").css("right",(minheight*aspect - width)/2 + "px");
  } else {
    $(".hero img").css("right","0px");
  }

  if(width > maxheight*aspect) {
    $(".hero img").css("top",(maxheight - width/aspect)/2 + "px");
  } else {
    $(".hero img").css("top","0px");
  }
}
$(function(){
  heroresize();
  // remove if you don't need dynamic resizing
  $(".hero").on("resize",heroresize);
});

Javascript可能会导致一些滞后/断断续续,因为调整大小事件可能会导致性能问题。如果您不需要担心动态调整大小,可以删除指定的行。

我在这里创建了一个可以玩的代码集:http://codepen.io/regdoug/pen/azxVwd请注意,codepen的最大高度为350px,因为这样可以在不调整大小的情况下查看效果。