0

我有这张图片,带有这个 CSS:

.containerImg {
    height: 420px;
    margin-top: 0;
    position: relative;
    width: 100%;
}

.img {
    margin: 0 auto;
    position: absolute;          /*unfortunately i can’t remove the position:absolute*/
}

和标记:

<div class="containerImg">
<img class="img" alt="" src="img//section_es_2442.jpg">
<div class="info">
        …
          </div>
<div class="clear"></div>
</div>

我发布它是为了让你可以看到 img 不是 .container 中唯一的东西

所以行为是图像应该使用所有 .container 尺寸并裁剪图像但保持原始比例,图像为 1600x500 (3,2:1)

那么,我该如何实现呢?

4

4 回答 4

1

如果我是你,我会使用 background-image 而不是 img 使用以下代码:

.containerImg {
    height: 420px;
    margin-top: 0;
    position: relative;
    width: 100%;
}

.img {
    margin: 0; 
    /*position: absolute;    I'll remove this */
    height: 420px;
    width: 100%; /*or use pixels*/
    background: transparent url('') no-repeat center top;
    overflow: hidden; /* not sure about you really need this */
}

和 :

<div class="containerImg">
  <div class="img" style="background-image: url('img/section_es_2442.jpg')"></div>
  <div class="info">
        …
  </div>
  <div class="clear"></div>
</div>

这个想法是你有一个类似 div 的视口,并且具有相同比例和大小的图像将是背景,如果图像更大,额外的大小将“喜欢”裁剪 :)

于 2011-10-31T10:35:51.677 回答
1

.containerImg {
     width: 120px;
     height: 120px;
     position: relative;
     overflow: hidden;
     }
     .cutImg {
     position: absolute;
     max-width: 120px;
     width: expression(this.width > 120 ? "120px" : true);
     max-height: 120px;
     height: expression(this.height > 120 ? "120px" : true);
     }

jQuery(window).load(function(){
    jQuery.each($(".cutImg"), function() {
    $(this).css("margin-left",(($(".containerImg").width()-$(this).width())/2));
    $(this).css("margin-top",(($(".containerImg").height()-$(this).height())/2));    
    });   
    });

<div class="containerImg"><img class="cutImg" src="images/sample1.jpg"/></div>
<div class="containerImg"><img class="cutImg" src="images/sample2.jpg"/></div>
于 2013-04-05T14:04:58.770 回答
0

不确定我是否理解您的意思,但您不能将图像设置为背景:

.containerImg {
    height: 420px;
    margin-top: 0;
    position: relative;
    width: 100%;
    background-image: url("img/section_es_2442.jpg");
    background-position: center;
}

或者如果它是动态构建style<div class="containerImg">

于 2011-10-31T09:43:09.620 回答
0
.img {
    margin: 0 auto;
    position: absolute;
    max-height: 420px; /* Same height as container's */
    height: expression(this.height > 420 ? "420px" : true;    
}

如果要检查宽度,则必须将容器的宽度设置为固定值...

快乐编码^^

于 2011-10-31T10:18:27.013 回答