视口 (ViewPort) 在视觉格式化模型中的作用
对于任何想要开发响应式网站的 Web 开发者来说,了解视口在视觉格式化模型中的作用至关重要。视口是浏览器窗口或移动设备屏幕上可见的区域。
在本教程中,我们将通过示例了解视口在视觉格式化模型中的作用。
什么是视觉格式化模型?
视觉格式化模型允许 Web 浏览器决定如何在网页上显示 HTML 内容。它提供了内容的可视化效果。
视觉格式化模型根据视口区域、其他一些因素以及 CSS 属性(例如边距、填充、边框等)在网页上显示内容。
视口的作用
视口在视觉格式化模型中的主要作用是决定可见区域。当设备屏幕尺寸发生变化时,可见区域也会随之变化,内容的视口也会随之变化。
早期的网页仅供电脑使用,因此网站缺乏响应式设计。但如今,网站 60% 的流量来自移动设备和平板电脑。因此,需要根据视口区域显示网页内容。
简单来说,视口用于确定可见区域,并根据可见区域进行响应式网页设计。
语法
用户可以按照以下语法将视口添加到网站。
<meta name="viewport" content="width=device-width, initial-scale=1.0">
我们可以使用 <meta> 标签将视口添加到网站。
属性
Name - 它使用 'viewport' 值来表示该标签作为视口。
Content - 它设置网页的宽度,而 'device-width' 值将宽度设置为等于屏幕宽度。
Initial-scale - 它根据比例值放大或缩小网页。
现在,让我们通过示例了解视口在视觉格式化模型中的作用。
示例 1
在下面的示例中,我们在父 div 元素内创建了多个具有不同类名的 div 元素。此外,我们还使用元标记添加了视口。
在 CSS 中,我们设置了父 div 的宽度并设置了显示。用户可以更改浏览器窗口的大小,并观察它如何根据浏览器的视口排列内容。
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.parent {
width: 90%;
display: flex;
flex-wrap: wrap;
justify-content: space-evenly;
}
.first,
.second,
.third,
.fourth {
width: 230px;
height: 100px;
margin: 20px;
background-color: aqua;
border: 2px solid blue;
border-radius: 12px;
}
</style>
</head>
<body>
<h2>Using the <i> viewport meta tag </i> to make responsive website</h2>
<div class = "parent">
<div class = "first"> </div>
<div class = "second"> </div>
<div class = "third"> </div>
<div class = "fourth"> </div>
</div>
</body>
</html>
示例 2
在下面的示例中,我们有一个容器 div 元素,其中包含图像和文本 div 元素。我们添加了 CSS,使图像占用 50% 的空间,文本占用 40% 的空间。
此外,我们使用媒体查询设计了适用于移动设备的网页。用户可以在移动设备和桌面设备上观察输出效果。此外,还可以从以下代码中删除视口后观察输出效果。
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container {
width: 90%;
margin: 0 auto;
border: 1px solid black;
padding: 10px;
display: flex;
}
.image {width: 50%; margin-right: 3%;}
.text {
width: 40%;
font-size: 1.5rem;
padding: 20px;
margin-left: 3%;
}
img {width: 100%; height: 300px;}
/* media query for mobile devices */
@media (max-width: 600px) {
.container {flex-direction: column;}
.image {width: 100%; margin-right: 0; margin-bottom: 20px;}
.text {width: 90%; margin-left: 0;}
}
</style>
</head>
<body>
<h2>Using the <i> viewport meta tag </i> to make responsive website</h2>
<div class = "container">
<div class = "image">
<img src = "https://picsum.photos/seed/picsum/200/300" alt = "Random image">
</div>
<div class = "text">
The image is picked up from the picsum website. It allows us to get random image of specified dimensions. Change the viewport size of your browser to checkout the responsive design.
</div>
</div>
</body>
</html>
结论
我们在开发网页时学习了视口 (viewport) 的使用。它用于根据屏幕宽度获取可见区域的大小,并可视化内容。
如果我们使用媒体查询来实现网站响应式显示,而不使用视口元标记,那么网页将保持原样,而不会变成响应式显示。
相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

