提问人:PhpDoe 提问时间:10/21/2022 最后编辑:PhpDoe 更新时间:7/13/2023 访问量:4665
为什么CSS高度:100vh;在移动设备上超出视口高度的规则?
Why is the CSS height:100vh; rule exceeding the viewport height on mobile devices?
问:
为了使我的标题适合所有视口,我使用了经典的 CSS 规则,它就像一个魅力......除了在我的手机上。height: 100vh;
实际上,在屏幕底部,标题比视口高(比应有的高 20px 或 30px)。由于此问题,标题底部的某些内容在移动设备上是隐藏的。
我尝试使用 Chrome DevTools 控制台修复该错误,但是当我使用移动视图(所有设备)时,一切都很好。
问题似乎来自我手机上的浏览器地址栏(我使用的是 Chrome)。
我错过了什么?如何正确修复?
这里有html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Test</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>Lorem ipsum</header>
<main>
<p>Lorem ipsum</p>
</main>
</body>
</html>
这里是CSS:
@charset "UTF-8";
/** RESET CSS **/
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section, main{display:block;}
*{margin:0;padding:0;border:0;list-style:none;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;}
header{
height: 100vh;
background: green;
font-size: 22px;
}
答:
(答案来自这个问题的评论部分。
CSS 规则是让任何框填满视口的所有空间,这正是我们对她的要求。height: 100vh;
当在适用于移动设备的 Safari 或 Chrome 浏览器上,浏览器的地址栏增加了一个额外的空间时,事情就会出错 :显然,这不是一个错误,而是一个故意的功能。
要解决这个问题,可以使用 html、 来代替 。header { height: 100vh; }
html, body, body > header { height: 100%; margin: 0; padding: 0; }
该框现在正在填充所有可用的高度,并且不会添加任何额外的空间:浏览器的地址栏高度不会添加到框中。
必须为父级(html 和 body)设置 CSS 规则,并且必须使用 use,否则会出现额外的空格。height: 100%;
margin: 0; padding: 0;
以下是更新和更正的CSS:
@charset "UTF-8";
/** RESET CSS **/
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section, main{display:block;}
*{margin:0;padding:0;border:0;list-style:none;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;}
html,
body,
body > header{
height: 100%;
margin: 0;
padding: 0;
}
header{
/*height: 100vh;*/
background: green;
font-size: 22px;
}
而不是使用单位尝试CSS规则,这是动态视口高度,大小将根据移动浏览器的UI状态自动调整,即浏览器地址栏是否可见。
它在当前版本的浏览器中得到了很好的支持(2023 年 7 月)。vh
height: 100dvh
评论
html, body { margin: 0; }
* { margin: 0; }
*
<body>
*
html, body, body > header { height: 100%; margin: 0; }