Jednostki CSS

Jednostki CSS

CSS has several different units for representing length.

Many CSS properties accept "length" values, such as width,margin,padding,font-size etc.

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

Example

Set different length values using px (pixels):

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 unitsandRelative units.

Absolute length

Absolute length units are fixed, and the length represented by any absolute length will be displayed exactly 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, for example, for print layout (print layout).

Unit Description TIY
cm Centimeter Spróbuj!
mm Millimeter Spróbuj!
in Inch (1in = 96px = 2.54cm) Spróbuj!
px * Pixel (1px = 1/96th of 1in) Spróbuj!
pt Point (1pt = 1/72 of 1in) Spróbuj!
pc Pica (1pc = 12 pt) Spróbuj!

* Pixels (px) are relative to the viewing device. For devices with low dpi, 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 the font size of the element (font-size) (2em means twice the current font size) Spróbuj!
ex Relative to the x-height of the current font (rarely used) Spróbuj!
ch Relative to the width of "0" (rarely used) Spróbuj!
rem Relative to the font size of the root element (font-size) Spróbuj!
vw Relative to the viewport* width 1% Spróbuj!
vh Relative to the viewport* height 1% Spróbuj!
vmin Relative to the viewport* smaller size 1% Spróbuj!
vmax W stosunku do większego rozmiaru viewport o 1% Spróbuj!
% W stosunku do elementu nadrzędnego Spróbuj!

Wskazówka:Jednostki em i rem mogą być używane do tworzenia idealnych rozszerzalnych układów!

* Viewport (Viewport) = rozmiar okna przeglądarki. Jeśli viewport ma szerokość 50 cm, to 1vw = 0.5 cm.

Obsługa przeglądarek

Liczby w tabeli oznaczają pierwszą przeglądarkę, która w pełni obsługuje tę jednostkę długości.

Jednostki długości
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