将未知大小的大图像放在较小的div内,并隐藏溢出

问题描述:

我想将一个img放在一个div (无javascript )和无背景图片的中心。

I would like to center an img inside a div without javascript and without background-images.

以下是一些示例代码

<div> 
    <img src="/happy_cat.png"/> 
</div>




  • 我不知道img的大小,能够超出父元素的宽度

  • 我不知道父div的宽度(它是100%)

  • 父div

  • 图片大于父元素且父元素溢出:

  • 只需支援现代浏览器

    • I don't know the size of the img and it should be able to exceed the width of the parent
    • I don't know the width of the parent div (it is 100%)
    • The parent div has a fixed height
    • The image is larger than the parent and the parent has overflow:hidden
    • Only need to support modern browsers
    • 所需的结果。 (忽略不透明度等,只要注意定位)。

      Desired result. (Ignore opacities etc, just note the positioning).

      我知道这可以很容易地用背景图片,但这不是一个选择我。我也可以使用javascript,但它似乎是一个非常沉重的方式来实现这一点。

      I know this can be done easily with background images but that isn't an option for me. I could also use javascript but it seems like a very heavy handed way to achieve this.

      谢谢!

      杰克

这样做:

.img {
   position: absolute;
   left: 50%;
   top: 50%;
   -webkit-transform: translateY(-50%) translateX(-50%);
}

这假定父div相对定位。我认为这是有效的,如果你想.img相对定位而不是绝对。只需删除位置:absolute 并将顶部/左侧更改为 margin-top $ c>。

This assumes that the parent div is positioned relatively. I think this works if you want the .img relatively positioned rather than absolutely. Just remove the position: absolute and change top/left to margin-top and margin-left.

您可能需要添加浏览器支持 transform code> -moz-transform 等。

You'll probably want to add browser support with transform, -moz-transform etc.