CSS响应式布局
定义
响应式布局又称为流式布局,旨在实现不同宽度的终端(手机、平板)浏览网页时展示不同的分布方式。
实现响应式布局的方法
通过媒介查询实现响应式布局,媒介查询一共有3种方式,分别为:
- @media查询
@media mediatype and/not/only (改变的条件){
css样式
}
或者@import导入
@import url("xxx.css") mediatype and/not/only (条件);
或者链接
<link rel="stylesheet" type="text/css" href="xxx.css" media="mediatype and/not/only (条件)" />
参考文章:https://www.zhihu.com/question/304514636/answer/2250651484
- rem
html{
font-size: 100px;
}
.box{
width: 1rem;
}
//动态为根元素设置字体大小
function init () {
// 获取屏幕宽度
var width = document.documentElement.clientWidth
// 设置根元素字体大小。此时为宽的10等分
document.documentElement.style.fontSize = width / 10 + 'px'
}
//首次加载应用,设置一次
init()
// 监听手机旋转的事件的时机,重新设置
window.addEventListener('orientationchange', init)
// 监听手机窗口变化,重新设置
window.addEventListener('resize', init)
- flexible.js
响应式布局举例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.header{
background-color: lightblue;
text-align: center;
width: 100%;
height: 100px;
}
.container{
width: 100%;
overflow: hidden;
}
.left,.middle,.right{
height: 400px;
float: left;
}
.left{
width: 20%;
background-color: lightsalmon;
text-align: center;
}
.middle{
width: 50%;
background-color: mediumorchid;
text-align: center;
}
.right{
width: 30%;
background-color: navajowhite;
text-align: center;
}
.footer{
background-color: lightpink;
text-align: center;
width: 100%;
height: 100px;
}
@media screen and (max-width:980px){
.right{
display: none;
}
.left{
width: 50%;
}
.middle{
width: 50%;
}
}
</style>
</head>
<body>
<div class="header">头部</div>
<div class="container">
<div class="left">左侧</div>
<div class="middle">中间</div>
<div class="right">右侧</div>
</div>
<div class="footer">底部</div>
</body>
</html>
响应式布局的注意点
- 响应式布局以百分比作为单位,不写具体的宽度
- 设置图片随着屏幕大小自动缩放:
img{
max-width:100%;
}
问题:介绍一下响应式布局
知识点:响应式布局的原理、响应式布局的注意点