常用
%
百分比
px
像素 (計算機屏幕上的一個點)
em
相對于當前對象內文本的字體尺寸。例如:
1em 等于當前的字體尺寸;
2em 等于當前字體尺寸的兩倍。
如果某元素以 12pt 顯示,那么 2em 是24pt。
在 CSS 中,em 是非常有用的單位,因為它可以自動適應用戶所使用的字體。
rem
使用rem同em一樣皆為相對字體大小單位,不同的是rem相對的是HTML根元素。
rem中的“r”代表“root”,這意味著設置當前元素的字體大小的基準為根元素,大多數情況下,我們會設置在html元素上。
<style>
html {font-size: 12px;}
div {font-size: 1.5rem;}
</style>
<body>
<div>Test-01 (12px * 1.5 = 18px)
<div>Test-02 (12px * 1.5 = 18px)
<div> Test-03 (12px * 1.5 = 18px) </div>
</div>
</div>
</body>
當然,rem單位不僅應用在字體上,還可以實現到CSS 網格系統中。
不常見
vh 和 vw
在進行響應式布局時,我們常常會使用百分比來布局,然而CSS的百分比不總是解決每個問題的最佳方案,CSS的寬度相對于離它最近的父元素的寬度。 如果你想使用視口的寬度、高度而不是父元素的寬高,可以使用vh和vw單位。
1vh = viewportHeight * 1/100;
1vw = viewportWidth * 1/100;
使用vh、vw就可以保證元素的寬高適應不同設備。
vmin 和 vmax
vw和vh對應于viewport的width和height,而vmin和vmax分別對應于width、height中的最小值和最大值,例如如果瀏覽器的寬/高被設置為1000px/600px,那么
1vmin = 600 * 1/100;
1vmax = 1000 * 1/100;
ex 和 ch
ex、ch單位與em、rem相似之處在于都依賴于font-size,但是ex、ch還依賴于font-family,基于font-specific來計算。 引用w3C規范:
**ex unit
** Equal to the used x-height of the first available font. [CSS3-FONTS]The x-height is so called because it is often equal to the height of the lowercase "x". However, an ‘ex
’ is defined even for fonts that do not contain an "x". The x-height of a font can be found in different ways. Some fonts contain reliable metrics for the x-height. If reliable font metrics are not available, UAs may determine the x-height from the height of a lowercase glyph. One possible heuristic is to look at how far the glyph for the lowercase "o" extends below the baseline, and subtract that value from the top of its bounding box. In the cases where it is impossible or impractical to determine the x-height, a value of 0.5em must be assumed.
ch unit Equal to the used advance measure of the "0" (ZERO, U+0030) glyph found in the font used to render it.
這兩種單位,有許多用途,大部分是用于印刷時的微調整。例如,sup、sub元素分別顯示上標和下標,但是我們可以使用position和bottom模擬:
<style type="text/css">
body { margin: 0; padding:0;}
.sup { position: relative; bottom: 1ex;}
.sub { position: relative; bottom: -1ex;}
</style>
<div>
AaB<span class="sup">b</span>
CcXxD<span class="sub">d</span>EeFf
</div>
其他
in
英寸
cm
厘米
mm
毫米
pt
磅 (1 pt 等于 1/72 英寸)
pc
12 點活字 (1 pc 等于 12 點)