7

演示

有时我会使用与此方法类似的方法创建一个正方形(或任何矩形,实际上),它会在任何大小下尊重其比率。

我想要的是:

  • 以防止正方形在高度较小的设备(即横向手机)上延伸到视口之外

建议的解决方案

  • 使用将正方形的宽度限制为视口高度的百分比max-width: 90vh
  • 期望比率得到尊重

CSS

    .square {
      position: relative;
      height: 0;
      padding-bottom: 100%;
      overflow: hidden;
    }

    .square-inner {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
    }

    .mw { max-width: 90vh;} /* solution, but makes things break */

HTML

    <div class="square mw">
        <div class="square-inner"></div>
    </div>

应该发生什么

  • 在高度较小的视口中,正方形的最大宽度应为视口高度的 90%

实际发生的情况:

  • 视口高度小于正方形宽度时:
    • 宽度受vh值限制
    • 高度是根据正方形的宽度计算的,如果它没有被限制在vh
    • 我们得到一个垂直长的矩形

规范说相对值是根据“包含块”计算的,在我看来,它应该是容器的当前宽度。

浏览器行为:

  • Chrome 29.0.1547.65:如所述
  • Firefox 23.01:如所述
  • Opera:根本不尊重 vh未经 Opera 16+ 验证

我是否错误地解释了规范,或者这可能是浏览器供应商实施中的错误?

4

2 回答 2

1

问题在于同时使用 % 和 vh 的长度。

尝试这个:

工作示例

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  font-family: sans-serif;
  font-weight: 100;
}

.neat {
  width: 50%;
  max-width: 600px;
  min-width: 320px;
  margin: 0 auto;
}

.col {
  float: left;
  padding: 2rem;
  width: 90vh;    /*** Important bit changed width:50%; to width:90vh; ***/
  max-width: 50%; /*** Important bit added max-width:50%; ***/
}

.square {
  position: relative;
  height: 0;
  padding-bottom: 100%;
  overflow: hidden;
}

.square-inner {
  position: absolute;
  background-color: #333333;
  color: white;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 1.5rem;
}

.mw {
  max-width: 90vh;
}
于 2013-09-06T15:15:19.927 回答
0

I don't think Opera supports vh,and there are known issues. I'm wondering if this bug is affecting what you're seeing: http://code.google.com/p/chromium/issues/detail?id=124331.

于 2013-09-06T14:28:21.543 回答