相对填充和vh单位 - 错误或规范误解?

时间:2013-09-06 13:08:04

标签: css css3 viewport-units

DEMO

有时我会使用类似于this method的方法创建一个正方形(或任何矩形,真的),以尊重任何尺寸的比例。

我想要的是什么:

  • 防止在高度较小的设备上延伸到视口外的方块 即手机景观

建议的解决方案

  • 使用max-width: 90vh
  • 将square的宽度限制为视口高度的百分比
  • 期望比例受到尊重

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%

实际发生的事情:

  • viewport 高度小于square的宽度时:
    • 宽度受vh
    • 约束
    • 如果被约束为vh
    • ,则根据平方宽度计算高度
    • 我们得到一个垂直长矩形

The spec说相对值是从'包含块'计算出来的,对我而言似乎应该是容器的当前宽度。

浏览器行为:

  • Chrome 29.0.1547.65:如上所述
  • Firefox 23.01:如描述
  • Opera:完全不尊重vh 未通过Opera 16 +验证

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

2 个答案:

答案 0 :(得分:1)

问题在于使用%和vh两种长度。

试试这个:

<强> Working Example

* {
  -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;
}

答案 1 :(得分:0)

我认为Opera不支持vh,并且存在已知问题。我想知道这个错误是否会影响你所看到的内容:http://code.google.com/p/chromium/issues/detail?id=124331