如果你是一名前端開發工程師,一般px和em使用頻率比較高。但是今天本文的重點是介紹一些我們使用很少、甚至麼有聽說的單位。
<style type="text/css">
.box {
height: 100vmin;
width : 100vmin;
}
</style>
<body>
<div class="box" style="background-color: #f00">
fdasjfdlas
</div>
</body>
<style type="text/css">
body {
margin: 0;
padding:0;
}
.box {
/*寬屏顯示器width > height*/
height: 100vmin;
width : 100vmax;
}
</style>
<div class="box" style="background-color: #f00">
fdasjfdlas
</div>
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>