目录
介绍
媒体查询(Media Queries)是 CSS3 中引入的一种 CSS 技术。它允许开发者根据不同的设备特性(如屏幕宽度、高度、分辨率、设备方向等)来应用不同的 CSS 样式,从而实现响应式网页设计,让网页在各种设备上都能呈现出最佳的显示效果。
参考链接:https://www.w3school.com.cn/css/css3_mediaqueries.asp
基本语法
@media mediatype and (mediafeature) {
CSS-Code;
}
mediatype 表示媒体类型 (默认为all)
值 | 描述 |
---|---|
all | 用于所有媒体类型设备 |
用于打印机 | |
screen | 用于计算机屏幕、平板电脑、智能手机等 |
speech | 用于屏幕阅读器 |
mediafeature 表示媒体特性
例如:width(宽度)、height(高度)等。
and 将媒体特性与媒体类型或其他媒体特性组合
基本使用
只有一个媒体特性时:
@media screen and (min-width: 600px) {
// 当屏幕宽度为600px或更小时的样式
}
有多个媒体特性条件时:
@media screen and (min-width: 600px) and (max-width: 1200px) {
// 当屏幕宽度在600px到1200px之间的样式
}
同时运用在多个不同屏幕大小的媒体时:
@media screen and (min-width: 600px) and (max-width: 1200px),(max-width: 599px) {
// 当屏幕宽度在600px到1200px之间和599px或更小的样式
}
示例
示例效果
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 全局样式重置 */
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
/* 容器样式 */
.container {
padding: 30px;
background-color: rgb(242, 247, 249);
box-sizing: border-box;
height: 100%;
}
.top {
width: 100%;
background-color: rgb(63, 63, 63);
margin-bottom: 20px;
}
.middle {
width: 100%;
height: 750px;
margin-bottom: 20px;
overflow: auto;
}
.left-box {
width: 100%;
background-color: rgb(255, 228, 229);
border: 3px solid rgb(219, 0, 0);
box-sizing: border-box;
}
.right {
background-color: rgb(255, 228, 229);
border: 3px solid rgb(219, 0, 0);
box-sizing: border-box;
}
.bottom {
width: 100%;
background-color: rgb(156, 0, 0);
}
/* 大屏幕(宽度大于 768px)样式 */
@media screen and (min-width: 769px) and (max-width: 1024px), (min-width: 1025px) {
.top {
height: 100px;
}
.middle {
height: 750px;
overflow: auto;
}
.left {
width: 30%;
height: 100%;
float: left;
}
.left-box {
height: 100px;
margin-bottom: 20px;
}
.right {
width: 30%;
height: 100%;
float: right;
}
.bottom {
height: 100px;
clear: both;
}
}
/* 小屏幕(宽度小于等于 768px)样式 */
@media screen and (max-width: 768px) and (min-width: 320px) {
.container {
padding: 20px;
}
.top {
height: 10%;
}
.middle {
height: auto;
}
.left {
width: 100%;
float: none;
}
.left-box {
height: 50px;
margin-bottom: 10px;
}
.right {
width: 100%;
height: 250px;
float: none;
margin-bottom: 10px;
}
.bottom {
height: 10%;
}
}
</style>
</head>
<body>
<div class="container">
<div class="top"></div>
<div class="middle">
<div class="left">
<div class="left-box"></div>
<div class="left-box"></div>
<div class="left-box"></div>
</div>
<div class="right"></div>
</div>
<div class="bottom"></div>
</div>
</body>
</html>