主题
  • 默认模式
  • 浅蓝色模式
  • 淡绿色模式
  • 深夜模式

CSS 单位

在 CSS 中,有着多种用于表示长度的单位,这些单位在样式设置中扮演着关键角色。

可用于设置长度的属性包括widthheightmarginpaddingfont-sizeborder-width等。

长度是由数字和单位组成,如12px、2em等,数字和单位之间不能有空格,如果长度为0,单位可以省略。

长度单位有两种类型:绝对长度单位相对长度单位


绝对长度

绝对长度单位是固定的,用任何一个绝对长度表示的长度都将恰好显示为这个尺寸,不适合跨平台使用。

单位 描述 示例 TIY
px 像素(1px = 1/96 英寸) width: 100px; 试一试
pt 点(1pt = 1/72 英寸,常用于打印) font-size: 12pt; 试一试
in 英寸(1in = 96px = 2.54cm) width: 3in; 试一试
cm 厘米 margin: 1cm; 试一试
mm 毫米 padding: 5mm; 试一试

相对长度

相对长度单位规定相对于另一个长度属性的长度。相对长度单位在不同平台之间缩放表现得更好。

单位 描述 示例 TIY
% 相对于父元素的百分比 width: 50%; 试一试
em 相对于元素的字体大小(font-size)(2em 表示当前字体大小的 2 倍) padding: 1em; 试一试
rem rem(root em 的缩写),相对于根元素(<html>)的字体大小font-size font-size: 1.2rem; 试一试
vw Viewport Width,视窗宽度,1vw=视窗宽度的1% width: 50vw; 试一试
vh Viewport Height,视窗高度,1vh=视窗高度的1% height: 100vh; 试一试
vmin vw和vh中较小的那个 font-size: 4vmin; 试一试
vmax vw和vh中较大的那个 font-size: 4vmax; 试一试
ch 相对于字符 "0" 的宽度 width: 20ch; 试一试

* 视口(Viewport)= 浏览器窗口的尺寸。如果视口宽 50 厘米,则 1vw = 0.5cm。


适用场景

  • 响应式布局(remvwvh%
  • 字体缩放(remem更可控)
  • 全屏布局(100vh用于全屏高度)

浏览器支持

表格中的数字注明了完全支持该长度单位的首个浏览器版本。

Chrome 浏览器 IE 浏览器 Firefox 浏览器 Safari 浏览器 Opera 浏览器
em, ex, %, px, cm, mm, in, pt, pc 1.0 3.0 1.0 1.0 3.5
ch 27.0 9.0 1.0 7.0 20.0
rem 4.0 9.0 3.6 4.1 11.6
vh, vw 20.0 9.0 19.0 6.0 20.0
vmin 20.0 12.0 19.0 6.0 20.0
vmax 26.0 16.0 19.0 7.0 20.0


评论区 0
发表评论
教程介绍
CSS 参考手册全面涵盖选择器、盒模型,文本属性等,助您快速检索 CSS 使用方法。
85 章节
115 阅读
0 评论
教程目录

CSS 参考手册

CSS 属性(字母排序) CSS 属性(功能排序) CSS 浏览器支持 CSS 选择器 CSS 函数 CSS 可动画性 CSS Web安全字体 CSS 单位 CSS 颜色 CSS 颜色值

CSS 属性

align-content align-items align-self all animation animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function aspect-ratio backdrop-filter backface-visibility background background-attachment background-blend-mode background-clip background-color background-image background-origin background-position background-position-x background-position-y background-repeat background-size block-size border border-block border-block-color border-block-end border-block-end-color border-block-end-style border-block-end-width border-block-start border-block-start-color border-block-start-style border-block-start-width border-block-style border-block-width border-bottom border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-collapse border-color border-end-end-radius border-end-start-radius border-image border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-inline border-inline-color border-inline-end border-inline-end-color border-inline-end-style border-inline-end-width border-inline-start border-inline-start-color border-inline-start-style border-inline-start-width border-inline-style border-inline-width border-left-style border-right-style border-top-left-radius border-top-right-radius border-top-style