CSS媒体查询中使用的高度是指?
在 CSS 媒体查询中使用的高度(如 @media screen and (max-height: 800px)
) 对应的是视口的高度,而不是 window.screen.height
。视口高度是指浏览器窗口内可见内容区域的高度,不包括浏览器的工具栏、地址栏等非内容区域。
具体解释
@media screen and (max-height: 800px)
是媒体查询,它针对视口的高度进行响应式设计。视口的高度指的是浏览器窗口内显示页面内容的区域高度,可以通过window.innerHeight
或document.documentElement.clientHeight
获取。window.screen.height
是整个屏幕的高度,包括操作系统的任务栏、浏览器的工具栏等所有元素的高度。这个值一般不用于媒体查询,因为它不能准确反映浏览器内容区域的高度。
示例代码
下面是一个示例,演示如何使用媒体查询基于视口高度进行响应式设计:
1<!DOCTYPE html>
2<html lang="en">
3<head>
4<meta charset="UTF-8">
5<meta name="viewport" content="width=device-width, initial-scale=1.0">
6<title>Media Query Example</title>
7<style>
8 body {
9 font-family: Arial, sans-serif;
10 padding: 20px;
11 }
12
13 .box {
14 width: 100%;
15 height: 300px;
16 background-color: lightblue;
17 text-align: center;
18 line-height: 300px;
19 }
20
21 @media screen and (max-height: 800px) {
22 .box {
23 background-color: lightcoral;
24 line-height: normal;
25 padding-top: 20px;
26 }
27 }
28</style>
29</head>
30<body>
31 <div class="box">Resize the window height to see the effect</div>
32</body>
33</html>
34
在上面的代码中,当视口高度小于或等于 800px 时, .box
的背景颜色会变为 lightcoral
,并且文本对齐方式会改变。
检查视口高度
你可以在 JavaScript 中检查视口高度,并在控制台中输出,以便更好地理解它与 window.screen.height
的区别:
1console.log("Viewport height (window.innerHeight): " + window.innerHeight);
2console.log("Viewport height (document.documentElement.clientHeight): " + document.documentElement.clientHeight);
3console.log("Screen height (window.screen.height): " + window.screen.height);
4
运行这段代码,可以看到视口高度和屏幕高度的不同。
总结
媒体查询中的高度(如 @media screen and (max-height: 800px)
)对应的是视口高度,而不是屏幕高度 ( window.screen.height
)。视口高度是浏览器窗口内可见内容区域的高度,是响应式设计时常用的尺寸标准。
上一篇:
整理了ES7到ES14的新特性
相关笔记