响应式布局的核心,能够检测视口的宽度,然后编写差异化的 css 样式调整网页的布局方式。
响应式布局原理:根据 UI 设计稿需求合理设置响应断点,配合媒体查询书写差异化CSS样式。
响应断点是指媒体查询所采用的视口的宽度。作用:将屏幕尺寸划分成若干的区间。
/* 写法一:内嵌式 */
@media 逻辑符 媒体类型 and (媒体特性) {
执行的 css 代码
}
/* 写法二:外链式 */
"stylesheet" media="逻辑符 媒体类型 and (媒体特性)" href="xx.css" >
/* 视口宽度最小为320px,最大为640px时,呈现样式 */
@media (min-width: 320px) and (max-width: 640px) {
body {
background: #f00;
}
}
/* 视口宽度最小为640px,最大为1024px时,呈现样式 */
@media (min-width: 640px) and (max-width: 1024px) {
body {
background: #00f;
}
}
/* 视口宽度最小为1024px,最大为1600px时,呈现样式 */
@media (min-width: 1024px) and (max-width: 1600px) {
body {
background: #0f0;
}
}
浏览器解读代码时,实时对当前设备进行检测
@media 规则对应的样式。@media 样式要放在默认样式的后面,根据css特性,后面的样式会覆盖前面的样式。
<html>
<head>
<link rel="stylesheet" href="css/index.css" />
<style> 当前默认样式 style>
<link rel="stylesheet" media="(min-width: 320px) and (max-width: 640px)" href="css/media.css" />
head>
<body>body>
html>
| 类型名称 | 值 | 描述 |
|---|---|---|
| 屏幕 | screen | 带屏幕的设备 |
| 打印预览 | 打印预览模式 | |
| 阅读器 | speech | 屏幕阅读模式 |
| 不区分类型 | all | 默认值,包括以上3种情形 |
@media screen and (min-width: 1024px) and (max-width: 1600px) {
body {
background: #0f0;
}
}
| 特性名称 | 属性 | 值 |
|---|---|---|
| 视口的宽和高 | width、height | 数值 |
| 视口最大宽或高 | max-width、max-height | 数值 |
| 视口最小宽或高 | min-width、min-height | 数值 |
| 屏幕方向 | orientation | portrait: 竖屏 landscape: 横屏 |
/* 横屏 */
@media (orientation: landscape) {
h1::before {
content: '现在是横屏状态';
color: #f00;
}
}
/* 竖屏*/
@media (orientation: portrait) {
h1::before {
content: '现在是竖屏状态';
color: #00f;
}
}



@media (resolution: 2dppx) {
h1::after {
content: '2倍屏';
color: #f00;
}
}
@media (resolution: 3dppx) {
h1::after {
content: '3倍屏';
color: #00f;
}
}


通过正则判断是否为移动端
function idApp () {
// 是否是苹果
if (/iphone/i.test(navigator.userAgent)) {
return true;
}
// 是否是安卓
if (/android/i.test(navigator.userAgent)) {
return true;
}
// 是否是 windows phone
if (/windows phone/i.test(navigator.userAgent)) {
return true;
}
return false;
}
// 如果是移动端就跳转到移动端页面
if (isApp()) {
location.href = 'https://m.js.com/';
} else { // 否则就跳转到PC端页面
location.href = 'https://www.js.com/';
}