【问题标题】:Image in div, center full size responsivediv中的图像,中心全尺寸响应
【发布时间】:2014-08-08 10:45:44
【问题描述】:

我有一个 div,它根据浏览器宽度改变宽度,响应式。 div 中的图像在我网站的最广泛版本中最接近原始图像的宽度/高度。

当浏览器窗口变小时,我希望图像的高度保持不变,但宽度溢出被隐藏。图像应该在 div 中居中。这可能吗?

  1. 全尺寸
  2. 手机版

例如http://postimg.org/image/v16lb0rft/

【问题讨论】:

  • 您是否事先知道图像的宽度,或者您希望这适用于任何图像宽度?
  • 根据难度,我可以坚持上传相同宽度的图像。如果可能,宽度应该不同。

标签: html css responsive-design


【解决方案1】:

有可能,只需使用媒体查询。例如:

@media screen and (max-width: 640px) {
  #yourImage{
      overflow-x: hidden;
  }
}

【讨论】:

    【解决方案2】:

    有一个很棒的 jQuery 插件叫做 backstretch。通常它用于制作完整的背景图像,如here (clothing website)。但它也可以用于任何大小的小 div。 Backstretch.js

    【讨论】:

      【解决方案3】:

      如果硬编码图像的宽度不是问题,那么这应该可以。

      img#your-img {
          margin: 0 calc(50% - (/* the width of img#your-img */ / 2));
          overflow: hidden;
      }
      

      我希望这会有所帮助,祝你好运!

      【讨论】:

        【解决方案4】:

        我一直试图找到解决这个问题的方法很长一段时间,终于遇到了这个问题:

        HTML:

        <div class="image-wrapper">
            <img src="http://placehold.it/350x200">
        </div>
        

        CSS:

        .image-wrapper {
            /* Height 0, padding-bottom, and overflow hidden
            give the wrapper height since it won't get a height
            from it's child being positioned absolutely */
            height:0;
            padding-bottom:65%;
            position:relative;
            overflow:hidden;
            width:100%; /* your dimension here (can be px or %) */
        }
        .image-wrapper img {
            display:block;
            height:100%;
            left:50%;
            position:absolute;
            top:50%;
            width:auto;
        
            /* Negative translate instead of negative margins */
            -webkit-transform: translate(-50%, -50%);
            -moz-transform: translate(-50%, -50%);
            -ms-transform: translate(-50%, -50%);
            -o-transform: translate(-50%, -50%);
            transform: translate(-50%, -50%);
        }
        

        我已经对此进行了测试,并且可以正常工作。如果 IE 对您很重要,您可能会倒霉,但我希望这会有所帮助!

        Here is a fiddle

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-27
          • 1970-01-01
          • 2013-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-04
          • 2019-10-19
          相关资源
          最近更新 更多