本文章设计问题

页面设计需要在不同的设备上显示

布局只用float+定位,不使用flex

不能很好的使用rem作为设计单位

掌握响应式布局,弹性等常见布局

媒体查询

基本认识

为不同的尺寸的屏幕设定不同的CSS样式。(移动端设备更为常见)
案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
div{
width:150px;
height:200px;
}

@media screen and (min-device-width:100px) and (max-device-width:300px){
div{
background-color:red;
}
}

@media screen and (min-device-width:301px) and (max-device-width:500px){
div{
background-color:pink;
}
}

当屏幕宽度为100到300的时候,背景颜色是红色。当屏幕宽度为301px到500px的时候,背景颜色是粉红色。

@media screen and ..的screen指的是屏幕显示

@media常用参数

属性名称 作用
width、height 浏览器可视宽度、高度
device-width 设备屏幕的宽度
device-height 设备屏幕的高度

内部样式表引入方式

1
2
3
4
5
6
7

<style media="(min-device-width:100px) and (max-device-width:300px)">
div{
background-color:red;
}

</style>

外部样式表link引入

1
2
<link href="style.css" rel="stylesheet">
<link href="style.css" rel="stylesheet" media="(min-device-width:100px) and (max-device-width:300px)">

flex弹性盒子(布局)

为什么用flex?

flex提供了很大的灵活性。

更加符合响应式设计的特点。

对于flex的认识,可以看阮一峰的Flex布局教程。

rem

rem的作用和使用方法

相对于根元素的字体大小的单位。

1
2
3
4
5
6
7
html{
font-size:16px; /* 默认都是16px。通常情况下使用10px*/
}

div{
font-size:1rem; /* 相当于16px */
}

rem与em的区别

案例

自适应布局

  1. 原来的方法是不同设备对应不同的html文件,布局自适应也可以。这种方法不能说被淘汰,但是现在有更好的方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>
const redirect=()=>{
//获取设备的信息(用户代理)
let userAgent = navigator.userAgent.toLowerCase();
// 正则表达式,判断设备类型
let device =/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|widnows mobile/;
//使用正则判断
if(device.test){
//跳转移动端页面
window.location.href="mobile.html";
}else{
//跳转pc端页面
window.location.href="pc.html";
}
}

redirect();
</script>
  1. 使用css媒体查询

响应式布局

布局特点:确保一个页面在所有终端上,都能显示出令人满意的效果。

设计思路:使用%或rem作为单位。

%结合flex布局

rem结合flex布局

特点:为了保证在各种屏幕上的不失真,就要根据实际屏幕宽度做等比例换算

通过屏幕大小改变字体大小

1
2
3
4
5
6
7
8
const c=()=>{
let clientWidth = document.documentElement.clientWidth; /*获取设备的高度*/
let fontSize = (20*(clientWidth/320) > 40?40+"px":(20*(clientWidth/320)+"px"));
document.documentElement.style.fontSize=fontSize;
}

windows.addEventListener("load",c);
windows.addEventListener("resize",c);