问题不在于vh
单位,而在于min-height
我找到了一个半工作的纯 CSS 解决方案:
min-height: 100vh;
height: 100px;
height
即使内容不够高,额外的内容也会使 IE 垂直填充屏幕。缺点是如果内容比视口长,IE 将不再包装内容。
由于这还不够,我在 JS 中做了一个解决方案:
检测
这个函数测试错误:true
意味着它是错误的。
function hasBug () {
// inner should fill outer
// if inner's height is 0, the browser has the bug
// set up
var outer = document.createElement('div');
var inner = document.createElement('div');
outer.setAttribute('style', 'display:-ms-flexbox; display:flex; min-height:100vh;');
outer.appendChild(inner);
(document.body || document.documentElement).appendChild(outer);
// test
var bug = !inner.offsetHeight;
// remove setup
outer.parentNode.removeChild(outer);
return bug;
}
使固定
修复包括手动设置height
元素的px
function fixElementHeight (el) {
// reset any previously set height
el.style.height = 'auto';
// get el height (the one set via min-height in vh)
var height = el.offsetHeight;
// manually set it in pixels
el.style.height = height + 'px';
}
元素的高度将设置为其内容的高度。height
在 IE中用作辅助min-height
,使用在纯 CSS 解决方案中观察到的行为。
用法
一旦定义了这两个函数,就可以这样设置:
if(hasBug()) {
// fix the element now
fixElementHeight(el);
// update the height on resize
window.addEventListener('resize', function () {
fixElementHeight(el);
});
}
演示
function hasBug () {
// inner should fill outer
// if inner's height is 0, the browser has the bug
// set up
var outer = document.createElement('div');
var inner = document.createElement('div');
outer.setAttribute('style', 'display:-ms-flexbox; display:flex; min-height:100vh;');
outer.appendChild(inner);
(document.body || document.documentElement).appendChild(outer);
// test
var bug = !inner.offsetHeight;
// remove setup
outer.parentNode.removeChild(outer);
return bug;
}
function fixElementHeight (el) {
// reset any previously set height
el.style.height = 'auto';
// get el height (the one set via min-height in vh)
var height = el.offsetHeight;
// manually set it in pixels
el.style.height = height + 'px';
}
var output = document.getElementById('output');
output.innerHTML = hasBug()?'Browser is buggy':'Browser works correctly';
var el = document.getElementById('flex');
if(hasBug()) {
// fix the element now
fixElementHeight(el);
// update the height on resize
window.addEventListener('resize', function () {
fixElementHeight(el);
});
}
.half-screen {
display:-ms-flexbox;
display: flex;
min-height: 50vh;
padding: 10px;
background: #97cef0;
}
.content {
padding: 10px;
background: #b5daf0;
}
The inner box should fill the outer box vertically, even if the browser is buggy.
<div class="half-screen" id="flex">
<div class="content" id="output">
Text
</div>
</div>