iframe中的CSS vh单位 [英] CSS vh units inside an iframe
问题描述
我正在尝试在iframe中使用CSS vh
单位。我发现它们以某种方式缩放到iframe的大小。换句话说,100vh不是窗口高度。它被设置为iframe的高度。
I'm trying to use CSS vh
units inside of an iframe. I'm finding that they are scaled to the size of the iframe somehow. In other words, 100vh isn't the windowheight. It's set to the height of the iframe.
这看起来是否正确?
是否有解决方法?
推荐答案
我知道这是一个老问题,但随着人们走向 vh
单位,这个问题会变得更加普遍。
I know this is an old question, but as people move toward the vh
unit, this question will become much more common.
为了澄清,这是一个问题的例子。我们有一个HTML文件加载 iframe
:
To clarify, here's an example of the problem. We have an HTML file that loads an iframe
:
<!DOCTYPE html>
<html>
<head></head>
<style>
iframe {
height: 50vh;
width: 100%;
}
</style>
<body>
<iframe src="iframe.html"/>
</body>
</html>
及其 iframe
:
<!DOCTYPE html>
<html>
<head></head>
<style>
div {
height: 50vh;
width: 100%;
background: blue;
}
</style>
<body>
<div></div>
</body>
</html>
这里要注意的重要一点是 iframe
和 iframe的
div
元素被指定为高度 50vh
。预期的行为可能是 iframe
尊重父上下文的视口高度或宽度。相反,结果如下所示:
The important thing to note here is that both the iframe
and the iframe's
div
element are designated as having a height of 50vh
. The intended behaviour may be that the iframe
honor the parent context's viewport height or width. Instead, the result looks like this:
那个是的,蓝色元素的高度约为浏览器窗口的25%,而不是预期的50%( iframe
的100%)。虽然我们可能希望 iframe
尊重其父视口,但这个例子很好地证明了它的不直观性,尽管肯定会使 v *
对于 iframe
'd in的内容更有价值的单位。问题与如何确定视口高度有关。
That is, the height of the blue element is ~25% of the browser window, instead of the expected 50% (100% of the iframe
). Although we may wish the iframe
to respect the viewport of its parent, this example makes a good case for how unintuitive that may be, though it surely would make the v*
units more valuable for content being iframe
'd in. The problem has to do with how viewport height is determined.
来自规范:
视口百分比长度是相对于初始包含块的大小。当初始包含块的高度或宽度发生变化时,它们会相应缩放。
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.
iframe
,浏览器窗口可以是包含块,因为它们都是有效的视口。视口不仅限于浏览器窗口,而是定义为用户查阅文档的屏幕上的窗口或其他查看区域。
Both an iframe
and the browser window can be the initial containing block, as they are both valid viewports. A viewport is not limited to the browser window, but instead is defined as a window or other viewing area on the screen through which users consult a document.
iframe
创建嵌套浏览上下文,因此具有自己的视口。
An iframe
creates a nested browsing context when inserted into a document, and thus has its own viewport.
所以是的,这是预期的行为 - 遗憾的是没有纯CSS的解决方法 - 但是,www139提供了一个如何使用JavaScript完成此操作的示例。当使用 v *
单位控制许多元素的大小时,问题就开始了。
So yes, this is the intended behaviour - and unfortunately there is no pure CSS workaround - however, www139 has provided an example of how this can be accomplished using JavaScript. The problem with this begins when many elements' size are controlled using v*
units.
这篇关于iframe中的CSS vh单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!