【问题标题】:How to frame a 100% width image to locked ratio?如何将 100% 宽度的图像设置为锁定比例?
【发布时间】:2015-01-28 09:26:39
【问题描述】:

我希望在 16:9 比例的框架内显示 100% 宽度的图像。图像应在框架内居中并响应屏幕大小调整。理想情况下,我希望能够只使用 CSS 来做到这一点。

【问题讨论】:

    标签: html css


    【解决方案1】:

    结合多个 SO 答案,我能够使用以下样式使其工作。框架的尺寸在 .grid_6 中设置为 100% 宽度,在 .grid_6::after 中设置为 56.25% 高度。

    JS 小提琴:http://jsfiddle.net/stroz/fz2ez4uv/2/

    HTML

    <div class="thumb grid_6">
        <img src="http://placekitten.com/g/200/300" />
    </div>
    

    CSS

    .grid_6 {
        width: 100%;
        overflow:hidden;
        position:relative;
    }
    
    .grid_6::after {
      padding-top: 56.25%; /* percentage of containing block _width_ */
      display: block;
      content: '';
    }
    
    .thumb img {
        display: block;
        width:100%;
        height:auto;
        position: absolute;
        top: -9999px;
        bottom: -9999px;
        left: -9999px;
        right: -9999px;
        margin: auto;
    }
    

    此解决方案结合了以下问题中概述的方法:

    How to keep image aspect ratio inside a %width div?

    Scale a div to fit in window but preserve aspect ratio

    【讨论】:

      【解决方案2】:
      .aspect { max-width: 100%; }
      .aspect.dims16by9:before {
          content: '';
          display: block;
          width: 100%;
          padding-bottom: 56.25%; // 9/16
      }
      .aspect.dims4by3:before {
          content: '';
          display: block;
          width: 100%;
          padding-bottom: 75%; // 9/16
      }
      

      少混入:

      .aspectRatio(@widthAspect, @heightAspect) {
          @aspect: @heightAspect/@widthAspect * 100;
          max-width: 100%;
      
          &:before {
              content: '';
              display: block;
              width: 100%;
              padding-bottom: ~"@{aspect}%";
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-06-30
        • 1970-01-01
        • 2018-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-06
        • 1970-01-01
        • 2017-02-24
        相关资源
        最近更新 更多