响应式网页设计是一种网页开发方法,旨在创建能够适应和响应不同屏幕尺寸和设备的网站。
响应式设计的主要目标是在广泛的平台上提供最佳且一致的用户体验,包括台式电脑、笔记本电脑、平板电脑和智能手机。
下图显示了响应式网页设计如何允许布局适应各种用户设备,而不会损害用户体验。

CSS 媒体查询
媒体查询是 CSS 规则,它们根据各种条件(例如屏幕尺寸、分辨率、方向或其他设备特性)应用特定的样式和布局调整。
媒体查询对于创建响应式和自适应的网页设计至关重要,这些设计在不同设备和屏幕尺寸上看起来和功能都达到最佳状态。
让我们看一个例子。
@media (min-width: 768px) {
/* This style rule will only apply when the width
of the viewport is at least 768px */
.container {
width: 50%;
}
}
在此,包含在媒体查询中的 CSS 将仅在设备最小宽度为 768px 时应用。
响应式列布局
列布局是指在网页上以多列排列内容。这使我们能够以结构化且具有视觉吸引力的方式组织和呈现信息。
有几种列布局配置:3 列、2 列和 1 列布局。
让我们看看如何创建响应式列布局。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CSS Column Layout</title>
</head>
<body>
<header>HEADER</header>
<main>
<div class="column column1">COLUMN 1</div>
<div class="column column2">COLUMN 2</div>
<div class="column column3">COLUMN 3</div>
</main>
<footer>FOOTER</footer>
</body>
</html>
/* making a three column layout */
main {
display: flex;
flex-wrap: wrap;
height: 100px;
text-align: center;
}
.column1 {
/* width takes 20% of the flex container */
width: 20%;
background-color: orange;
}
.column2 {
/* width takes 60% of the flex container */
width: 60%;
background-color: yellow;
}
.column3 {
/* width takes 20% of the flex container */
width: 20%;
background-color: greenyellow;
}
header,
footer {
text-align: center;
background-color: pink;
}
浏览器输出

在上面的示例中,flex
属性允许我们创建三列布局。
这种布局通常用于台式机和笔记本电脑,以便在不同列中排列不同类型的内容。
例如,在新闻网站上,三栏布局可以用于在一栏中显示标题,在另一栏中显示特色文章,在第三栏中显示广告。
现在,使用 flex 属性和媒体查询,我们可以将上述三列布局更改为两列布局。
@media screen and (max-width: 768px) {
/* set column1 and column2 to 50% width each */
.column1,
.column2 {
width: 50%;
}
/* set column3 to 100% width */
.column3 {
width: 100%;
}
}
浏览器输出

上述 CSS 样式将三列布局更改为适用于平板电脑和较小设备的双列布局。
最后,对于宽度较小的移动设备,我们可以设置以下样式来实现单列布局。
@media screen and (max-width: 800px) {
.column1,
.column2,
.column3 {
width: 100%;
}
}
浏览器输出

通过这种方式,媒体查询用于为各种设备创建响应式网页布局。