我试图在 iframe 中使用 CSS 的 vh
单位。但是我发现它们会以某种方式按比例缩放到 iframe 的大小。换句话说,100vh 并不等于窗口高度,而是设置为 iframe 的高度。
这是否正确?
是否有解决方法?
我知道这是一个老问题,但随着人们向vh
单位转移,这个问题将变得更加普遍。
为了澄清问题,这里有一个示例。我们有一个加载iframe
的HTML文件:
<!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
遵守父级上下文视口的高度或宽度。但是,结果看起来像这样:
也就是说,蓝色元素的高度约为浏览器窗口的25%,而不是预期的50%(即iframe
的100%)。虽然我们希望iframe
遵守其父级视口,但这个例子很好地说明了这可能是多么不直观,尽管这对于使用v*
单位来嵌入iframe
的内容肯定会使其更有价值。该问题与如何确定视口高度有关。
从规范中可以得知:
视口百分比长度相对于初始包含块的大小。当初始包含块的高度或宽度改变时,它们会相应地缩放。
当iframe
和浏览器窗口均可成为初始包含块时,二者都是有效的视口。视口不仅限于浏览器窗口,而是定义为用户通过屏幕查看文档的窗口或其他查看区域。
当嵌入到文档中时,iframe
会创建一个嵌套浏览上下文,因此是其自己的视口。
所以,这是预期的行为-不幸的是,没有纯CSS解决方法-但是,www139提供了一个使用JavaScript可以实现这一点的示例。使用v*
单位控制许多元素大小的问题也从这里开始。
window.addEventListener('load',function(){
initializeV();
function initializeV(){
//1% of the parent viewport width (same as 1vw):
var vw = window.parent.innerWidth/100;
//1% of the viewport height (same as 1vh):
var vh = window.parent.innerHeight/100;
//assign width and height to your v unit elements here
}
window.parent.addEventListener('resize',function(){
//when the browser window is resized; recalculate
initializeV();
});
});
编辑(2018年12月):在评论中,有人要求提供一个示例。我无法提供精确的示例,因为Stackoverflow上的codepens加载的框架源与页面不同。但是,我可以模仿效果。对于实际应用,请参考上面的代码片段。此片段仅旨在说明其工作原理。
Practical Application. Uses the concept explained above but without frame reference.
window.addEventListener('load',function(){
initializeV();
function initializeV(){
//note: I can't use window.parent becuase the code snippet loads on a different frame than the parent page. See the other snippet for a practical example. This snippet is meant to merely illustrate the effect.
//1% of the parent viewport width (same as 1vw):
var vw = window.innerWidth/100;
//1% of the viewport height (same as 1vh):
var vh = window.innerHeight/100;
//this is where the magic happens. Simply set width/height/whatever to a multiple of vw/vh and add 'px'. Dimensions must be in pixels since the vw/vh measurement is based on pixels.
document.getElementById('test').style.width = 30*vw+'px';
document.getElementById('test').style.height = 50*vh+'px';
//assign width and height to your v unit elements here
}
window.addEventListener('resize',function(){
//when the browser window is resized; recalculate
initializeV();
});
});
#test{
background:red;
}
<div id="test"></div>
elem.style.dimension = 50*vh+'px';
将 vh/vw 测量乘以所需数字(50*vh 实际上是 50vh 单位),然后加上 'px'。必须以像素为单位进行测量,因为这是 vh/vw 测量基于的单位系统。 - www139
window.innerWidth
和window.innerHeight
。 - www139