首页 前端知识 响应式布局的五种方法

响应式布局的五种方法

2024-03-27 10:03:14 前端知识 前端哥 709 799 我要收藏

响应式布局的五种方法

  • 1.百分比布局
  • 2.rem布局
  • 3. 媒体查询 @media screen
  • 4. flex布局
  • 5.vw 和 vh


响应式布局是同一页面在不同的屏幕上有不同的布局,即只需要一套代码使页面适应不同的屏幕。

1.百分比布局

1.有父元素就相对于父元素
2.没有父元素就相对于视口的大小

举一个例子

<!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>
*{
margin: 0;
padding: 0;
}
.box2{
width: 80%;
height: 100px;
background: red;
}
.box{
width: 50%;
height: 100px;
background: yellow;
}
.box1{
width: 50%;
height: 50%;
background: blue;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
<div class="box2"></div>
</body>
</html>
复制

2.rem布局

rem(font size of the root element)是指相对于根元素的字体大小的单位,rem只是一个相对单位

rem和em的对比

  1. rem和em都是相对单位
  2. rem相对于根元素
  3. em相对于父元素

例如

<!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> %和rem 布局</title>
<style>
html {
font-size: 30px;
}
.box {
font-size: 10px;
}
.box2 {
width: 10rem;
height: 10rem;
background-color: plum;
}
.box {
width: 10em;
height: 10em;
background-color: aquamarine;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
<div class="box2"></div>
</body>
</html>
复制

3. 媒体查询 @media screen

例如

<!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>@media screen</title>
<style>
.box {
width: 10rem;
height: 10rem;
background-color: pink;
margin-left: 20rem;
}
/* 如果屏幕的宽大于1200px,它执行此css */
@media screen and (min-width: 1200px) {
html {
font-size: 20px;
}
}
/* 如果屏幕的宽小于1200px,它执行此css */
@media screen and (max-width: 1200px) {
html {
font-size: 10px;
}
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
复制

4. flex布局

5.vw 和 vh

vw表示相对于视图窗口的宽度,vh表示相对于视图窗口高度,除了vw和vh外,还有vmin和vmax两个相关的单位。各个单位具体的含义如下:

例如

<!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>
*{
margin: 0;
padding: 0;
}
.box{
width: 100vw;
height: 100vh;
background: red;
}
.box1{
width: 50vw;
height: 50vh;
background: blue;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">
</div>
</div>
</body>
</html>
复制
转载请注明出处或者链接地址:https://www.qianduange.cn//article/4226.html
标签
评论
发布的文章
大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!