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

Css 保持图像的纵横比,但在达到最大/最小高度时进行裁剪,css,image,responsive-design,Css,Image,Responsive Design,我正试图使这张图像响应,它将调整大小,并保持它的纵横比在所有大小。然而,在650px以上,它的高度不会增加,只会裁剪顶部和底部以保持比例,而不会拉伸。此外,我希望图像的高度不会低于200px,只是左右。我希望图像也始终处于中心位置。以下是我到目前为止的情况: .英雄{ 宽度:100%; 最小高度:200px; 最大高度:650px; 位置:相对位置; } .英雄img{ 宽度:100%; 高度:自动; 最小高度:200px; 溢出:隐藏; 最大高度:650px; 职位:居留; } 非常感谢通

我正试图使这张图像响应,它将调整大小,并保持它的纵横比在所有大小。然而,在650px以上,它的高度不会增加,只会裁剪顶部和底部以保持比例,而不会拉伸。此外,我希望图像的高度不会低于200px,只是左右。我希望图像也始终处于中心位置。以下是我到目前为止的情况:


.英雄{
宽度:100%;
最小高度:200px;
最大高度:650px;
位置:相对位置;
}
.英雄img{
宽度:100%;
高度:自动;
最小高度:200px;
溢出:隐藏;
最大高度:650px;
职位:居留;
}

非常感谢

通过添加一些javascript,可以在
.hero
分区内动态调整图像的位置。此外,还可以使用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只监听调整大小事件,并调整相对定位图像的
top
right
属性,以保持图像居中。请注意,我使用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);
});
var heroresize=function(){
变量方面=1800./858,
最大高度=650,
最小高度=200,
宽度=$(“.hero”).width();
if(宽度<最小高度*纵横比){
$(“.hero img”).css(“右”,“最小高度*纵横比)/2+“px”);
}否则{
$(“.hero img”).css(“右”,“0px”);
}
如果(宽度>最大高度*纵横比){
$(“.hero img”).css(“顶部”,“最大高度-宽度/纵横比)/2+“像素”);
}否则{
$(“.hero img”).css(“top”,“0px”);
}
}
$(函数(){
heroresize();
//如果不需要动态调整大小,请删除
$(“.hero”)。打开(“调整大小”,heroresize);
});
Javascript可能会导致一些延迟/停顿,因为调整大小事件可能会占用大量的性能。如果不需要担心动态调整大小,可以删除指示的行


我创建了一个你可以在这里玩的代码笔:请注意,代码笔的最大高度为350px,因为这样你就可以看到效果,而不用调整太多大小。

我想不出一个简单的方法在CSS中实现这一点。如果你愿意使用一些JS,我可能会想出一个包含背景图像和JS的解决方案来设置
.hero
元素的高度。我确实想避免使用背景图像,但我不介意使用JS。
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);
});