CSS 尺寸单位大全

常用

%

百分比

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 点)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,786评论 1 92
  • 我们很容易无法摆脱的使用我们所熟悉的CSS技术,当新的问题出现,这样会使我们处于不利的地位。 随着Web继续的发展...
    yo_yo_阅读 352评论 0 0
  • 众所周知,当使用CSS技术的时候,很容被一些奇异问题给困住。而当我们面对新的问题时,这会让我们处于非常不利的位置。...
    cbw100阅读 724评论 0 12
  • CSS中有许多设置长度单位的属性,除了经常使用的px,em之外,还有一些不太经常使用的,但是作为一个前端工程师,也...
    SCQ000阅读 2,624评论 2 51
  • 早在辅导员发布新生通知的时候我就知道了这件事。“寻找最美的你”作为新生代表在新生典礼的时候上台发言。 说实...
    猫倩_Hero阅读 200评论 5 1