rem和em比较
1.相同点
都是相对单位,目的都是为了在不同的屏幕上显示的效果尽可能的一致,换句话讲就是在大屏幕上进行整体放大,小屏幕上进行整体缩小。
2.不同点
em 是相对当前元素设置font-size
,需要设置每个元素的font-size
,太零散,不好统一进行管理。
rem 是相对根元素(html标签)设置font-size
,只需要设置跟元素的font-size,便于统一管理。
使用流程
注: 在实际开发中,以美工获取的效果图,一般为2倍图
1.效果图中的物理像素转换为逻辑像素,2倍图除以2。
2.将转化后的逻辑像素(px)转化为rem/em单位。
需要除以一个基数(eg:html标签font-size
的值),这个基数可随意设置, 一般我们会将基数设置为屏幕宽度的十分之一。
demo
1.rem用法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>Document</title>
<style>
.container {
width: 10rem;
border: 1px solid #ccc;
}
.t {
width:10rem;
display: flex;
padding: 0 0.5rem;
margin-bottom: 32px;
}
.tl {
width: 3rem;
height: 6rem;
background: rgb(50, 37, 230);
}
.tr {
width: 6rem;
height: 6rem;
background: orangered;
}
.bt {
width: 10rem;
height: 3rem;
background: yellow;
margin-bottom: 0.5rem;
}
html {
/*在使用rem时,将px转换为rem时,是以html标签的font-size大小为依据和基数*/
font-size: 32px;
}
</style>
</head>
<body>
<div class="container">
<div class="t">
<div class="tl"></div>
<div class="tr"></div>
</div>
<div class="bt"></div>
</div>
</body>
</html>
2.em用法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>Document</title>
<style>
.container {
font-size: 32px;
width: 10em;
border: 1px solid #ccc;
}
.t {
font-size: 32px;
width: 10em;
display: flex;
padding: 0 0.5em;
margin-bottom: 32px;
}
.tl {
font-size: 32px;
width: 3em;
height: 6em;
background: rgb(50, 37, 230);
}
.tr {
font-size: 32px;
width: 6em;
height: 6em;
background: orangered;
}
.bt {
font-size: 32px;
width: 10em;
height: 3em;
background: yellow;
margin-bottom: 0.5em;
}
</style>
</head>
<body>
<div class="container">
<div class="t">
<div class="tl"></div>
<div class="tr"></div>
</div>
<div class="bt"></div>
</div>
</body>
</html>
效果图: