浏览器支持的 CSS 单位总共有15种,但是常用的只有 6 种:
px
px
像素 : 是绝对单位。rem, em, vw, vh, %
是相对单位。使用 px
定义的大小固定,在所有的屏幕上看起来都一样。实际可以用来设固定的 border 宽度等等。绝对单位和相对单位都有各自的用处,没有好坏之分。
vw 和 vh
vw
和 vh
分别相对于屏幕(严格来说是 viewport,窗口)的宽和高。例如,50vw
是屏幕宽度的一半,50vh
是屏幕高度的一半,依此类推。
%
%
相对于父元素,假如当前元素宽度为 50%
, 而它的父元素宽度为 50vw
,那么此元素的实际宽度为 50% * 50vw = 25vw
,所以实际宽度为屏幕宽度的 1/4
, 依此类推。设置字体大小时也是。
如果将元素的字体大小设置为百分比,它将是父元素字体大小的百分比。 如果对宽度值使用百分比,它将是父元素宽度的百分比。
if you set an element’s font-size as a percentage, it will be a percentage of the font-size of the element’s parent. If you use a percentage for a width value, it will be a percentage of the width of the parent.
rem
rem
中的 r 指的是 root 元素,即 <html>
元素。rem
是相对于 <html>
元素的字体大小的单位。所有的浏览器的<html>
font-size 默认都是 16px,因此 4rem
对应 64px
, 但是由于此数字 16
用于计算不那么方便,实际应用中可以使用一个小技巧:
html {
/* 62.5% of 16px = 10px */
font-size: 62.5%;
}
于是 16rem
马上就可以知道对应 160px
。
但是如果像下面这样直接设基本的字体大小为10px
:
html {
font-size: 10px;
}
那么rem
大小将会固定为10px
,浏览器用户将无法按需放大或者缩小字体。
The main reason I don’t declare html { font-size: 10px; }
is that if a visually impaired user has reset their base browser size (up or down), I want to respect that, so I want my site’s typography to scale proportionally to his default browser settings.
em
em
一般情况下相对于父元素的字体大小。
- | 相对于 |
---|---|
em | 对于印刷属性如 font-size, 相对于父元素字体大小。而对于其他属性如 width, 则是相对于当前元素自己的字体大小. |
如下的例子,先设 font-size,然后又设 width = 3em:
<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>
<link rel="stylesheet" href="normalize.css" />
<style>
.child {
font-size: 123px;
width: 3em;
border: 1px solid blue;
}
</style>
</head>
<body>
<button>text</button>
<div class="box parent">
<div class = "box child">
div-2
</div>
</div>
</body>
</html>
那么 width 实际将是 369px 如下图所示。不设此 font-size,width 将是 48px。
em
用于进行扩展或缩放时非常有用。
em,rem,%, 这几个相对单位,都可以用来设置元素的宽和高,以及字体大小。
省略。。。。。。。。。。。。。。。。。。
- https://stackoverflow.com/questions/32530787/what-is-the-root-element-for-rem
- https://stackoverflow.com/questions/24542508/default-html-font-size
- https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units
- https://stackoverflow.com/questions/28988445/css-62-5-why-do-developers-use-it