【问题标题】:Keeping aspect ratio of image but cropping when hitting max/min height保持图像的纵横比,但在达到最大/最小高度时裁剪
【发布时间】:2015-04-02 10:57:10
【问题描述】:

我正在尝试使此图像具有响应性,它会调整大小并在所有尺寸下保持纵横比。但是在 650px 以上,它的高度不会增加,只会裁剪顶部和底部以保持比例而不是拉伸。另外我希望图像高度不会低于 200 像素,而只是左右。我也希望图像始终处于中心位置。这是我目前所拥有的: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;
}

非常感谢

【问题讨论】:

  • 我想不出在 CSS 中实现这一点的简单方法。如果您愿意使用一些 JS,我可能会提出一个涉及背景图像和 JS 的解决方案来设置 .hero 元素的高度。
  • 我很想避免使用背景图片,但我不介意使用js。

标签: css image responsive-design


【解决方案1】:

通过添加一些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 可能会导致一些延迟/卡顿,因为调整大小事件可能会占用大量性能。如果您不需要担心动态调整大小,可以删除指示的行。

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

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 2021-02-09
    • 2021-06-12
    • 2015-06-13
    • 2011-12-27
    • 2015-05-22
    • 1970-01-01
    • 2015-07-28
    • 2018-09-28
    相关资源
    最近更新 更多