将未知大小的大图像放在较小的div内,并隐藏溢出 [英] Center a large image of unknown size inside a smaller div with overflow hidden

查看:113
本文介绍了将未知大小的大图像放在较小的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

      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.

      这篇关于将未知大小的大图像放在较小的div内,并隐藏溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆