หน่วยทาง CSS

หน่วยทาง CSS

CSS มีหลายหน่วยความยาวที่แสดงความยาว

หลาย CSS คุณสมบัติยอดนำรับค่า width,margin,padding,font-size etc.

Length is a number followed by a length unit, such as 10px,2em etc.

Example

Use px (pixels) to set different length values:

h1 {
  font-size: 60px;
}
p {
  font-size: 25px;
  line-height: 50px;
}

Try it yourself

There should be no spaces between numbers and units. However, if the value is 0, the unit can be omitted.

For some CSS properties, negative lengths are allowed.

There are two types of length units:Absolute unitandRelative unit.

Absolute length

Absolute length units are fixed, and the length represented by any absolute length will be displayed exactly as this size.

It is not recommended to use absolute length units on the screen because the screen size varies greatly. However, if the output medium is known, they can be used, such as for print layout (print layout).

Unit Description TIY
cm Centimeter ลองทดลอง
mm Millimeter ลองทดลอง
in Inch (1in = 96px = 2.54cm) ลองทดลอง
px * Pixel (1px = 1/96th of 1in) ลองทดลอง
pt Point (1pt = 1/72 of 1in) ลองทดลอง
pc Pica (1pc = 12 pt) ลองทดลอง

* Pixels (px) are relative to the viewing device. For low dpi devices, 1px is a device pixel (dot) on the screen. For printers and high-resolution screens, 1px represents multiple device pixels.

Relative length

Relative length units specify the length relative to another length property. Relative length units scale better between different rendering media.

Unit Description TIY
em Relative to element's font size (font-size) (2em means twice the current font size) ลองทดลอง
ex Relative to current font's x-height (rarely used) ลองทดลอง
ch Relative to "0" (zero) width ลองทดลอง
rem Relative to root element's font size (font-size) ลองทดลอง
vw Relative to viewport*width 1% ลองทดลอง
vh Relative to viewport*height 1% ลองทดลอง
vmin Relative to viewport*smaller size 1% ลองทดลอง
vmax Relative to viewport*larger size 1% ลองทดลอง
% เรlatively to parent element ลองทดลอง

คำแนะนำ:em 和 rem หน่วยขนาดสามารถใช้สร้างเครื่องแบบที่สามารถขยายได้!

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

浏览器支持

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

长度单位
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