The most familiar CSS unit is probably the pixel unit (PX), which is an absolute unit, meaning that a 10px text is the same size wherever it is placed. Units can affect a range of properties, from color to distance to size. There are many different forms of units in CSS, so let’s take a look at each of them.

1. Relative units

The relative unit is the length relative to another length. There are two main types of relative units in the CSS:

  • Font units are calculated according to font size. Common font relative units are em, REM, EX, CH;
  • Windows relative units, they are determined by window size. Common window units are VW, VH, vmax, and vmin.

Here’s a look at these common CSS units.

(1) EM and REM

Em is the most common unit of relative length, suitable for typesetting based on a particular type. According to CSS, 1em is equal to the value of the element’s font-size property.

Em is computed relative to the font size of the parent element. If the font size for inline text is not currently displayed, relative to the browser’s default font size. When DOM elements become more nested, and multiple levels of em are explicitly set for font size, the complexity of the computation becomes very high.

Of course, the above statement is not rigorous. Here’s an example:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .parent {
            width: 300px;
            height: 300px;
            font-size: 20px;
        }
        .child {
            border: 1em solid ;
        }
    </style>
</head>
<body>
    <div class="parent">
        <divClass ="child"> </div>
    </div>
</body>
</html>

Copy the code

Here we give the parent element a font size of 20px and the child element a border width of 1em. In this case, the child element border value is 20px, which is indeed relative to the parent element’s font size:

So if we set the font for the child element to 30px:

.child {
  font-size: 30px;
  border: 1em solid ;
}
Copy the code

As you can see, the border width of the child element is 30px, which is calculated relative to its size:

Therefore, it can be concluded that if the element has no font size, it will be evaluated based on the font size of its parent element. If the element has a font size, it will be evaluated based on its own font size.

In addition to font size, the em unit can be used for other attributes that use length, such as border-width, width, height, margin, padding, text-shadow, etc.

Therefore, the use of EM is complicated and may inherit the font size of any parent element. Use caution.

Rem is much simpler than EM, and is calculated based on the font size of the root element (root element) of the page. To modify the above example:

.child {
  font-size: 30px;
  border: 1rem solid ;
}

html {
	font-size: 25px;
}
Copy the code

As you can see, the border length has changed to 25px, based on the font size of the root HTML element:

Font size: 1rem works just as well as font size: initial, unless the size is set for the root element.

Using EM and REM gives us the flexibility to control the overall zoom in and out of elements, rather than a fixed size. When should YOU use EM and when should you use REM? You can choose according to their differences:

  • Both computed styles are displayed as PX in the client;
  • Rem is calculated relative to the font size of the root element HTML, em is calculated relative to the font size of the element;
  • Rem should be used when scaling according to the browser’s font size;
  • Use em based on the font size of the component, not the root element;
  • Rem can inherit font size values from browser font Settings, and EM can be affected by any inherited parent element font size.

(2) ex and CH

Ex and CH are both units for typography, and their size depends on the font size and font family attributes of the element.

  • Ex refers to the height of the small letter X in the font used. Therefore, if two fonts are not the same, then the value of ex is different. Because the height of the lowercase X is different for each font.
  • Ch is similar to EX, except that it is based on the width of the number 0. Will change as the font changes. The width of 0 is usually an estimate of the average character width of a font. Because ch is a unit of approximately equal width, it is useful when setting the width of a container, such as when a container wants to display a specified number of strings.

(3) VW, VH, Vmax and Vmin

These four units are window units, the so-called window, on the Web side refers to the visual area, the mobile side of the window refers to the layout window. If the window size changes, these values change with it. These four units refer to:

  • Vw: percentage of window width;
  • Vh: percentage of window height;
  • Vmax: larger VH and VW;
  • Vmin: Smaller VH and VW.

If the height of a browser is 800px, then 1vh is 8px. The size of vH and VW always depends on the height and width of the window.

Vmin and vmax are related to the maximum and minimum values of window width and height. If a browser is 500px high and 1200px wide, 1vmin is 5px and 1vmax is 12px.

These units are units of length, so they can be used anywhere units of length are allowed. These units are good for creating panoramic viewport interfaces, such as those on mobile devices, because elements vary based on viewport size and are not related to any element in the document tree.

Absolute units

In the CSS, absolute units include PX, pt, PC, cm, mm, and in. The absolute unit is a fixed value that reflects a real physical size. It is not affected by screen size or font. Their size depends on the value as well as the screen resolution (DPI, dots per inch). Px is one of our most common absolute units. These absolute units are converted as follows:

1in = The 25.4 mm = 2.54 cm = 6pc = 72pt =96px
Copy the code

(1) the px

Px stands for Pixels, which isn’t exactly the same as the Pixels on your display, especially in HIGH definition. Although CSS units scale appropriately depending on the browser, operating system, or hardware, and can vary depending on the resolution Settings of some devices or users, 96px is usually equal to one physical inch.

CSS defines the display of raster images (such as photos) as 1px by default. A “600×400” resolution photo will be “600px” and “400px”, so the image’s pixels will not match the display pixel, but the px unit. This allows the image to be completely aligned with other elements of the page.

A PX is often referred to as a CSS pixel. It is an absolute unit, but can also be considered a relative unit, since a pixel unit is relative to a device pixel. On the same device, the physical pixel represented by each CSS pixel can be changed; The physical pixel represented by each CSS pixel can vary between devices.

.box {
    width: 100px;
    height: 100px;
}
Copy the code

(2) the pt

Pt stands for Point. Often used in software design and typography (the end product of my front-end system is a PDF that needs to be printed, so I often use this unit). When using this unit, the results printed on paper are the same regardless of the resolution of the display.

Px is recommended for web page display, pt is recommended for print output.

(3) the PC

The whole PC is Picas, which means sending cards. Equivalent to the size of China’s new no. 4 type. Paika is also a printed term. One paika equals 12 points. Its conversion to PX is as follows:

1pc = 16px
Copy the code

(4) cm

Centimeters are called price after Centimeters. Its conversion to PX is as follows:

1cm = 37.8 px.
Copy the code

(5) mm

Millimeters are called Millimeters. Its conversion to PX is as follows:

1mm = 3.78 px.
Copy the code

(6) in

A. as B. as C. as D. as Its conversion to PX is as follows:

1in = 96px
Copy the code

3. Frequency unit

The CSS has two frequency units: Hertz (Hz) and kilohertz (kHz). Their conversion is as follows:

1kHz = 1000Hz
Copy the code

Typically, frequency units are used in listening or speaking cascading style sheets. Frequency can be used to change the pitch of a speech reading text. Low frequencies are the bass, high frequencies are the treble.

.low { 
  pitch: 105Hz; 
} 

.squeal { 
  pitch: 135Hz; 
}
Copy the code

Note that when the value is 0, the unit has no effect on the value, but the unit cannot be omitted. In other words, 0 hz, 0 KHZ are different. So, when you’re using frequency units, don’t just write 0. In addition, these two units are case insensitive.

4. Time unit

The CSS has two time units: second (s) and millisecond (ms). The two time units are newly added to the CSS. The conversion of the two units is as follows:

1s = 1000ms
Copy the code

Time units are used primarily in transitions and animations to define duration or delay times. The following two definitions are equivalent:

a[href] {
	transition-duration: 2.5 s;
}

a[href] {
	transition-duration: 2500s;
}
Copy the code

5. Units of resolution

The CSS has three resolution units: DPI, DPCM, and DPPX. These three units are new units of CSS3 China. They’re all positive, they’re not allowed to be negative. The conversion of these three units is as follows:

1dppx = 96dpi
1dpi0.39 DPCM
1dpcm2.54 dpi
Copy the code

The resolution unit is used for media query.

(1) the dpi

Dots per inch is the total number of dots per inch. Normal screens usually contain 72 or 96 dots, and screens larger than 192dpi are called high score screens.


@media screen and (min-resolution: 96dpi) {... }@media print and (min-resolution: 300dpi) {... }Copy the code

(2) DPCM

DPCM is called dots per rectification, which means the number of spots contained per centimeter.

@media screen and (min-resolution: 28dpcm) {... }@media print and (min-resolution: 118dpcm) {... }Copy the code

(3) the DPPX

Dots per Pixel, DPPX stands for the number of dots per pixel (PX). Since CSS px has a fixed ratio of 1:96, 1dppx equals 96dpi. It corresponds to the default resolution of the image displayed in CSS defined by the image resolution.

@media screen and (min-resolution: 2dppx) {... }@media screen and (min-resolution: 1dppx) and (max-resolution: 1.9 DPPX) {... }Copy the code

6. Units of Angle

The CSS has four Angle units: DEG, grad, rad, and turn. These Angle units are new to CSS3. Their conversion is as follows:

90deg = 100grad = 0.25 turn1.570796326794897 rad
Copy the code

These Angle units are generally used for element rotation operations, including 2D rotation, 3D rotation, and so on.

  • When the rotation value is positive, the element rotates clockwise;
  • When the rotation value is negative, the element rotates counterclockwise.

Normally, a full rotation is 360 degrees. So, all the angles are between 0 and 360 degrees. However, values beyond this range are also allowed, except they fall between 0 and 360 degrees. For example, a clockwise rotation of 420 degrees (450deg), a counterclockwise rotation of 270 degrees (-270deg), and a clockwise rotation of 90 degrees (90deg) all have the same effect and are classified as 90deg. But when using animation, these Angle values are very important.

The rotation of the CSS depends on the rotate(), rotate3D, skew() and other methods in the transform property. You just pass them the Angle of rotation.

In addition to rotation using angles, linear gradients often use Angle values:

background: linear-gradient(45deg.# 000.#fff);
Copy the code

(1) the deg

A deg is called a Degress. It stands for degrees. A circle has 360 degrees.

transform: rotate(2deg);
Copy the code

(2) grad

The full name for grad is Gradians, so there are 400 gradients in a circle.

transform: rotate(2grad);
Copy the code

(4) rad

Rad stands for Radians, 2 PI Radians in a circle.

transform: rotate(2rad);
Copy the code

(4) turn

Turns, Turns, Turns, Turns, Turns, Turns, Turns, Turns

transform:rotate(.5turn);
Copy the code

7. Percentage units

Percentage (%) is also one of our more common units, and can be used for all attributes that accept length values. However, different attributes may use this unit differently. But there needs to be a reference value, which means that the percentage value is a relative value.

Let’s look at the use of percentage units in common scenarios.

(1) Percentage in box model

The box model in CSS contains the following properties: width, max-width, min-width, height, max-height, min-height, padding, margin, etc. These attributes have different references when using percentages:

  • Width, max-width, min-width: when the value is a percentage, it is calculated relative to the width of the containing block;
  • Height, max-height, min-height: when the value is a percentage, it is calculated relative to the height of the contained block.
  • Padding, margin: if the value is a percentage, the horizontal value is calculated relative to the width of the containing block; If the value is vertical, it is computed relative to the height of the containing block.

(2) Percentages in the text

The CSS controls the properties of font size, line-height, vertical-align, and text-indent. These attributes have different references when using percentages:

  • Font-size: calculates according to the font size of the parent element;
  • Word-break: break-all;
  • Vertical-align: calculates according to line-height.
  • Text-indent: Evaluates by width if it is horizontal, by height if it is vertical.

(3) Percentage in positioning

In the CSS, top, right, bottom, and left that control position can all use percentages as units. The reference is the width and height of the containing block in the same direction. Contain blocks differ in different positions:

  • If the element is static or relative, the containing block is generally its parent;
  • If the element is absolute, the containing block should be the ancestor element whose nearest position is Absolute, relative, or fixed.
  • If the element is fixed, the containing block is a viewport.

(4) Percentage in transformation

Percentages can also be set in the translate and transform-origin values of the transform property in the CSS.

  • TranslateX () is computed from the width of the container
  • TranslateY () is computed based on the height of the container
  • The horizontal coordinate (x) in transform-Origin is calculated relative to the width of the container; Height of y relative to the container is computed

Note that there is also a z-axis function translateZ() in Translate. It does not accept values in percentage units.