常用
%
百分比
px
像素 (計算機屏幕上的一個點)
em
相對于當(dāng)前對象內(nèi)文本的字體尺寸腌紧。例如:
1em 等于當(dāng)前的字體尺寸击敌;
2em 等于當(dāng)前字體尺寸的兩倍。
如果某元素以 12pt 顯示,那么 2em 是24pt淌实。
在 CSS 中,em 是非常有用的單位猖腕,因為它可以自動適應(yīng)用戶所使用的字體拆祈。
rem
使用rem同em一樣皆為相對字體大小單位,不同的是rem相對的是HTML根元素倘感。
rem中的“r”代表“root”放坏,這意味著設(shè)置當(dāng)前元素的字體大小的基準(zhǔn)為根元素,大多數(shù)情況下老玛,我們會設(shè)置在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>
當(dāng)然,rem單位不僅應(yīng)用在字體上蜡豹,還可以實現(xiàn)到CSS 網(wǎng)格系統(tǒng)中麸粮。
不常見
vh 和 vw
在進行響應(yīng)式布局時,我們常常會使用百分比來布局镜廉,然而CSS的百分比不總是解決每個問題的最佳方案弄诲,CSS的寬度相對于離它最近的父元素的寬度。 如果你想使用視口的寬度娇唯、高度而不是父元素的寬高齐遵,可以使用vh和vw單位。
1vh = viewportHeight * 1/100;
1vw = viewportWidth * 1/100;
使用vh塔插、vw就可以保證元素的寬高適應(yīng)不同設(shè)備梗摇。
vmin 和 vmax
vw和vh對應(yīng)于viewport的width和height,而vmin和vmax分別對應(yīng)于width佑淀、height中的最小值和最大值留美,例如如果瀏覽器的寬/高被設(shè)置為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規(guī)范:
**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.
這兩種單位,有許多用途挚币,大部分是用于印刷時的微調(diào)整亮蒋。例如,sup妆毕、sub元素分別顯示上標(biāo)和下標(biāo)慎玖,但是我們可以使用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 點)