Illustrated CSS: Values and Units of CSS

w3cplus
33 min readJan 19, 2024

--

CSS Values and Units is another independent functional module of CSS. So far, this module has reached Level 4 ( CSS Values and Units Module Level 4 ). Today we will talk about the content of this module. For CSSers, values and units in CSS should not be unfamiliar, but most colleagues should focus on units. In fact, in this article, most of the content we involve is also about units, and we will only spend a little bit of content on the value part.

Value of CSS

Before discussing the value of CSS, let me show you a picture:

The above image is just one of our common CSS style rules.

In fact, CSS is a very magical discipline. Any rule we declare for CSS may include:

  • CSS selectors
  • CSS properties
  • CSS property values
  • CSS property value unit

Today we are going to talk about CSS property values and units. However, not every rule in CSS contains both CSS property values and units, because many property values only have values, not units. For example, the colorproperty in the figure above does not have units, but can be keywords, strings, functions, etc. The CSS values you may encounter when writing CSS include:

  • Numeric : length value <length>, used to specify the value of properties such as element width, border-width, font-size, etc., which may or may not have units
  • Percentage : Can be used to specify size or length, e.g. depending on parent container’s width, heightor default font-size
  • Color : used to specify background-color, color, etc
  • Coordinate position : the upper left corner of the screen as the coordinate origin to position the element, such as common background-position, top, right, bottomand leftproperties
  • Function : used to specify the background image or the gradual change of the background image, such as linear-gradient (), image-set (), etc

To summarize briefly: CSS properties have various values, which can be numeric, string, keyword, or function; at the same time, the value of CSS properties can have units or not Moreover, CSS values are not fixed, and the values corresponding to different properties will be slightly different, such as: widthproperty, its value can be a percentage value, or a value with a number and a unit; colorvalue can be a keyword, or a function value; font-sizecan be a percentage, a keyword, or a numerical value with a unit; line-heightcan be just a numerical value, a percentage value, or a numerical value with a unit, etc. Many properties are not listed one by one.

Units of CSS

As mentioned above, CSS property values have units and some do not. The units in CSS have a direct impact on CSS values. Because the units in CSS have a direct impact on the calculation of CSS values, there is a relationship diagram between units in CSS, as shown below.

In order to facilitate everyone’s better understanding and memorization of unit-related knowledge points in CSS, the following figure is reclassified according to the W3C specification.

Note that the above picture is a bit old, as described in “ Modern CSS “ “ Relative Units in Modern CSS “, so far, CSS relative length units are mainly divided into font relative length units , window relative length units and container query relative length units three:

  • Font relative length unit : Refers to the font measure using their element (for local font relative length) or root element (for root font relative length)
  • Window relative length unit : the length relative to the size of the browser window, such as vwand vh, etc
  • Container query relative length unit : the length relative to the size of the query container, such as cqwand cqh, etc

So in this article, we mainly focus on the commonly used units in CSS. We introduce the scenarios and usage details of these CSS units.

Absolute unit

Some units in CSS are absolute values and are not affected by any screen size or font. The display of these units may vary depending on the screen resolution because they depend on the DPI (dots per inch) of the screen. Absolute units are often used in some physical measurements. They are very useful when the environmental output is known. In CSS, absolute units include: px, in, cm, mm, pcand pt, among which pxis the most common absolute unit. So far, pxcan also be considered one of the mainstream units in CSS use.

The pixel unit is considered the basis for many other units of measurement. It provides consistent results in various devices. It is also considered the best device pixel , and this pixel length has nothing to do with the text screen pixels you see on the display. Because pxis actually a unit measured by angle, that is, the pixel angle .

For more information on device pixels, read Modern Web Layout ‘s Next Generation Responsive Web Design: Component-Driven Web Design .

Many times, pxis also often referred to as CSS pixel. It is an absolute unit, but it can also be regarded as a relative unit. Why? Because the pixel unit is relative to the device pixel. On the same device, the physical pixel represented by each 1CSS pixel can be changed (i.e. the relativity of the first aspect of CSS pixels); between different devices, the physical pixel represented by each 1CSS pixel can be changed (i.e. the relativity of the second aspect of CSS pixels).

According to Lingo’s explanation:

It is the basic unit of image display, not a definite physical quantity, nor a point or small square, but an abstract concept. Therefore, when discussing pixels, it is important to understand their context!

Different devices have different units for basic image sampling. The physical pixels on the display are equal to the dot pitch of the display, while the physical pixels of the printer are equal to the ink dots of the printer. The units for measuring dot pitch and printer ink dots are called PPIand DPI, respectively.

Because the size of the physical pixels of different physical devices is different, CSS believes that the browser should adjust the pixels in CSS so that the size of oneCSS pixel in the browser always looks similar on different physical devices, in order to ensure a consistent reading experience. To achieve this, the browser can directly convert according to the physical pixel size of the device, and the CSS specification uses "reference pixels" for conversion.

1reference pixel is the angle between the line of sight and the horizontal line when the output of a device with a resolution of 96DPIis viewed from an arm's length (i.e. 1inch 96points), and 1point (i.e. 1/96inch). It is not 1/96inch in length, but the angle between the line of sight and the horizontal line when the output of a device with a resolution of 96DPIis one unit (i.e. 1/96inch) from an arm's length. It is generally believed that the average human arm length is 28inches, so its perspective is:

(1/96)in / (28in * 2 * PI / 360deg) = 0.0213deg

Since CSS pixels are a unit of viewing angle, in actual implementation, they are basically converted based on device pixels for convenience. Browsers can directly obtain CSS pixels based on hardware devices.

A brief introduction to arm’s length: The typical distance between our eyes and the output of different devices is different. For example, computer monitors are usually arm’s length away, while reading and paper (corresponding to the output of printer devices) are usually closer. When watching TV, it will be farther away. For example, it is generally recommended that the diagonal of the TV screen be 2.5to 3times longer - if you are a 42inch color TV, it is about 3meters away.

This description is too theoretical for many CSSers, so let’s get back to reality. For example, if I have a box element in my project with a size of 150pxin width and height, we often use it like this in CSS:

.box {
width: 150px;
height: 150px;
}

Although it is said that the pixel should be the same in the display of the device and the monitor, it is becoming more and more incorrect. That is because, with the appearance of the station Retina screen, the DPRis different (device pixel ratio), and the display of the pixel and the monitor will be slightly different. For example, as shown in the following figure:

Therefore, in the mobile end design, most of the designs are designed with 2or 3times the size.

Although pxis the most common and frequently used absolute unit in CSS, in fact, there are other absolute units in CSS, such as in(inches), cm(centimeters), mm(millimeters), pcand pt, etc. Among them, in, cmand mmcan be directly converted to px:

  • 1in = 96px
  • 1cm = 37.8px
  • 1mm = 3.78px

And pcand ptand inare directly related:

  • 1in = 72pt
  • 1in = 6pc

If you want to convert ptand pcdirectly to px, you can use inas a bridge. For example:

  • 1in = 96px = 72pt, then 1px = 72/96 = 0.75pt
  • 1in = 96px = 6pc, then 1px = 6/96 = 0.0625pc

A simple diagram can be used to describe the relationship between absolute units.

In the specification, the absolute unit also has a new unit, which is not very common, namely Q, 1Qis equivalent to 25mm. It is used for printing typesetting.

Relative unit

Relative units and absolute units are different. Relative units are lengths relative to another length. Styles that use relative units are easier to leave one output environment and adapt to another. CSS relative units are mainly divided into two categories. One is the font relative unit, which is calculated according to the font-size; the other is the window relative unit, which is determined relative to the window size.

Font relative unit

The main font relative units are em, rem, ex, ch, cap, ic, lhand rlh. Among them, em, rem, exand chare more common font relative units. Here we will only introduce these common units.

em

Initially, the typesetting measurement was based on the size of the capital letter M of the font on that day. When changing the font-family, its size does not change, but when changing the size of the font-size, its size changes.

In CSS, without any CSS rules, the length of 1emis:

1em = 16px = 0.17in = 12pt = 1pc = 4.mm = 0.42cm

As we all know, every browser has a default font-sizesize, and this value is usually 16px(when the user does not modify the browser font size). This is why 1em = 16px.

EmAnother important point is that emis related to the font-sizeof their ancestor elements. Therefore, if the font-sizeof the ancestor element is set to 0.5em, and the font-sizeof its child elements is set to 1em, the calculated font-sizein this scenario will be 16 x 0.5 = 8px:

From the simple example above, we can see that as the nesting of DOM elements deepens and different levels explicitly set the value of font-sizeto em, it will increase the complexity of emcalculation and conversion, for example:

There is a certain formula for the conversion between pxand em, as follows:

1 ÷ 父元素的font-size × 需要转换的像素值 = em值

Note that when the font-sizeof the element itself is not explicitly set, the font-sizeof the parent element is taken.

We can also use JavaScript to write a simple conversion function:

function px2em(pixel,parentFontSize) {
return (pixel / parentSize) + 'em'
}

px2em(10, 16) // => 0.625em

The emunit applies not only to the font-sizeproperty, but also to other properties that can use <length>values, such as width, margin, padding, border-width, and text-shadow.

<length>is a CSS data format that represents distance dimensions. It consists of a <number>followed by a length unit, such as px, em, pt, in, etc. As with any CSS size, there are no spaces between numbers and units. If <number>is 0, the length unit after it is optional.

If you use emas the unit of the <length>value on a non- font-sizeproperty, it will be affected by the font-size of the element. There is a common understanding among many developers that emunits are relative to the font-sizeof the parent element. But in fact? They are relative to the font-size**of the element using the** emunit. The font-sizeof the parent element can affect the emvalue, but this happens purely because of inheritance.

As mentioned earlier, when using emunits for inheritance, it can be tricky to handle unit conversions.

Why do we need to deal with unit conversion? That’s because most of the design drafts we get are measured in units of px. In this way, when we convert the design draft to the Web page, we have a process of pxto em.

From the previous knowledge, we know that properties using emunits are determined by the font-sizeof the element. However, the element may inherit the font-sizeof its parent element, and the parent element may inherit the font-sizeof its parent element. Therefore, the font-sizein emunits may be affected by the font-sizeof any parent element. This argument has been verified in the above example.

Since the font-sizeof the element will change, the properties that use emunits on the element will also be affected accordingly. Let's take a look at the corresponding example:

div {
width: 20em;
height: 20em;
border: 1em solid;
padding: 3em;
}

The effect you see is as follows:

In this example, we did not explicitly set the font-sizein the divelement and its ancestor elements, so the font-sizeof this element inherits the browser's default font-size, which is 16px. Therefore, the emin the width, height, border-widthand paddingproperties will be calculated based on 16pxas the benchmark. Therefore, the final result is shown in the figure above. If we nest a child element divin the div, the result will be as follows:

Two divusing the property of em, the final result is the same, but the child element divoverflows the parent element div. If we explicitly set font-size: .5emin the child element div, the result will be another one:

In this regard, the emunit can better maintain and expand the size of components. For example, the properties of the size of the cgroup component, such as width, height, paddingand border-width, etc. When using emas the unit, if you want to adjust the size of the component, you can directly adjust the font-sizeof the component (if the element itself does not set the font-size, you can adjust the font-sizeof its ancestor elements). For example, as shown in the figure below, adjusting the font-sizecan be very flexible in the size of the cgroup component:

rem

Remis less complex than em, it is just the font-sizecalculation relative to the root element <html>. The W3C specification describes remas follows:

Font size of the root element!

Many times, we can use remas a substitute for em. Especially in the use of the font-sizeproperty, but remand emhave one biggest difference: any element with a value of 1remis equal to 16px , of course, the premise is that the browser's default font-size has not been reset by the user, or has not explicitly set the font-size value for the html element; in addition, rem can ignore the font-size of its parent element!

As can be seen from the above figure, even if the font-sizevalue is explicitly set in the body, it will not affect the font-sizeof its child element h3, and the font-sizeof h3is always calculated relative to the root element <html>.

In addition, remand emare somewhat similar, and properties that can accept <length>as a value can be in remunits, and they are calculated relative to the font-sizeof the root element html, and have nothing to do with the hierarchy of the DOM.

Em or rem

In actual development, many colleagues often ask:

em is good, or rem is good, which one should I choose better?

In fact, this is a highly controversial issue. Because in practice, some developers completely avoid using rem, claiming that using remwill make their components lack Modularization; other developers use remfor everything, because they like the convenience brought by rem. So what should be a better choice?

There is no best, only the most suitable!

When it comes to choosing between remor em, it is rational to use remor emin different places. In fact, many successful cases have also proven this point:

  • If this property is measured according to its font-size, you should select em
  • Everything else should use rem

Also, you can choose according to the differences between the two:

  • The style values computed by remand emin the Client ( computed style (Computed Style) ) will be explicitly px
  • remrelative to the root element html's font-sizecalculation, emrelative to the element font-sizecalculation
  • remcan inherit font-sizevalues from browser font settings, emmay be affected by any inherited parent element font-size
  • The use of emshould be based on the font-sizeof the component, not the font-sizeof the root element
  • When you don’t need to use emunits and need to scale according to the browser's font-sizesetting, you should use rem

Ex and ch

exand chare typographical units, which means their values depend on the element's font-family. When we use emand remunits, the browser calculates their values based on the element's font-size. Regardless of the font displayed on the screen, the browser calculates the same value. This is where exand chunits provide more flexibility. They require the browser to determine the referenced font-familybefore calculating the value and applying the style. Because the element's font-familystyle has a direct relationship and influence on the calculation of the exand chunit values.

In typographical terms, the xheight is determined by the height of the lowercase letters of the font. This is usually measured by its parent x, which has no rise or fall. The relationship between the font-sizeof the font and the xheight can tell you a lot about the proportions of the font.

The exunit values come from the xheight of the font context they calculate, and xheight is determined by two factors: font-family and font-size. In other words, they are equal to the xheight of a specific font at a specific font-size.

As shown above, font-familyfor Helvetica Neueset the font-sizeto 100px, so 1exis approximately equal to 52px.

chis similar to ex, but it does not depend on the height of x; it is based on the characters of the font, extracting their values from the width of the font's 0 shape, which also varies with the font. In this way, it is a bit arbitrary, and the width of 0is usually the average character width of the font, which is an estimate, so it will be a bit bad.

Since the chunit is an approximately equal-width unit, it is particularly useful to set the width of the container. For example, if you want the container to display a specific number of strings, you can use the chunit.

Modern CSS “ of the “ relative units in modern CSS “, modern CSS font relative units, in addition to the units mentioned above, there are other font relative units:

  • rex: value calculation relative to the exunit on the root element
  • rch: value calculation relative to the chunit on the root element
  • cap: equal to the cap-height of the first available font, which is approximately equal to the height of the capital Latin letter
  • rcap: Calculate the value of the capunit relative to the root element
  • lh: equal to the line-height of the element ( line-height)
  • rlh: Calculated relative to the value of lhunits on the root element, when used for the font-sizeor line-heightproperties of the root element, it refers to the initial values of these properties
  • iC: is the Eastern version of ch. It is the size of the CJK (Chinese, Japanese, and Korean) ideogram water( U + 6C34), so it can be roughly interpreted as "ideogram count". In cases where it is impossible or impractical to determine the size of ideograms, it must be assumed to be 1em
  • ric: value calculation relative to the icunit on the root element

Window relative unit

In CSS, besides font relative units, there are also window relative units, mainly vw, vh, vminand vmax. Before understanding window units, let's briefly understand the concept of windows, which will help us better understand window units.

On the PC side, the window refers to the visible area of the browser, while in the mobile end, it is relatively more complex and includes three windows: Layout Viewport , Visual Viewport , and Ideal Viewport :

And we want to say that the window unit in the window refers to: PC side refers to the browser visual area, mobile end is the layout window (Layout Viewport) :

With the concept of windows, we can better understand the units of windows in CSS. The main units of windows in CSS are:

  • vw: percentage of window width
  • vh: percentage of window height
  • vmin: currently smaller vwand vh
  • vmax: currently larger vwand vh

Using the following picture to describe, it will be clearer for everyone.

Let’s take a look at how window units are calculated. For example, if the height of the browser is 900px, the value obtained by 1vhis 9px. Similarly, if the display window width is 750px, the value obtained by 1vwis 7.5px. vhand vware always related to the height and width of the window, but vminand vmaxare related to the maximum or minimum values of the width and height of the window, depending on which is larger or smaller. For example, if the browser is set to 1100pxwidth and 700pxheight, 1vminwill be 7px, and 1vmaxwill be 11px. However, if the width is set to 800pxand the height is set to 1080px, 1vmin

Similarly, modern CSS has also added some new units to window relative units . With the emergence of CSS logical properties , window units have added viand vb:

  • vi: refers to the browser window internal connection axis size ( inline-size) of 1%
  • vb: Refers to 1%of the browser window block-size

Use the lvprefix in CSS to define the units of large windows, which include lvw, lvh, lvi, lvb, lvminand lvmax. Also use the svprefix to define the units of small windows, which include svw, svh, svi, svb, svminand svmax. Dynamic window units are defined with the dvprefix, which includes dvw, dvh, dvi, dvb, dvminand dvmax.

If you are interested in these new CSS units, please read the window relative units in the Modern CSS course Relative Units in Modern CSS !

Container relative unit

The CSS specification currently defines the following container query units:

  • cqw: query width, relative to the query container width calculation, that is, 1cqwis equal to the query container width 1%
  • cqh: query height, calculated relative to the height of the query container, that is, 1cqhis equal to the height of the query container 1%
  • cqi: query internal connection axis size, relative to the query container internal connection axis size calculation, that is, 1cqiis equal to 1%
  • cqb: query block axis size, relative to the query container block axis size calculation, that is, 1cqbis equal to the query container block axis size 1%
  • cqmin: query the minimum value, is to query the internal connection axis size cqior query the smaller value in the block axis size cqb
  • cqmax: query the maximum value, is to query the internal connection axis size cqior query the larger value in the block axis size cqb

Unit of angle

Speaking of angle units, in fact, what everyone is talking about is degree units. We may have learned a lot about them from daily life. Learning geometry in school, doing basic woodworking, entering outer space, or rotating an element in image editing software will all have angle-related figures.

In the real world, degrees are almost a unit of measurement for angles. It is also a popular role in the web and applies to various scenarios we will encounter. Fortunately, degrees in the real world and virtual world have many similarities.

Before we start looking at code snippets and how to use degree units in HTML, CSS, and JavaScript, let’s take a moment to recall what degrees are and introduce some basic concepts about degrees. First and foremost:

Perhaps you have seen a diagram like this before (actually a circle). It represents a complete rotation and all the angles we want to measure or specify. One big detail to remember is: A complete rotation is made up of 360 degrees . All angles will be between 0and 360degrees:

This doesn’t mean you can’t handle degree values outside of 0and 360. Negative numbers and values greater than 360degrees are allowed. It's just that they are always classified as 0and 360degrees. Take a look at the following two normalized variants:

In the first variant, the value we specify is actually -90degrees. The resulting angular path is clockwise and stops at the position of 270degrees ( 360 - 90 = 270). In the second variant, the value we specify is 420degrees. This means that we have to complete a full rotation ( 360degrees) and then continue rotating 60degrees. In most cases, the final degree value of the first variant is 270degrees, and the final degree value of the second variant is 60degrees. Whether the value of the angle is negative or not is irrelevant. In order to obtain the final angle value between 0and 360, the number of rotations is not important. Again, this only applies to most cases. In some cases, such as those involving animation, it is very important that we adopt the final angle degree value. We will talk about this later.

The above is the knowledge points about the basic theory of angle units. In fact, there are also many usage scenarios related to angles in CSS.

Rotation in CSS

One of the most common uses of angle is to set a rotation angle (degree) for rotating elements in CSS , relying on the rotate ()function in the CSS transformproperty, skew ()function, etc. Among them, pass an angle value to the rotate ()function to make the element rotate accordingly. For example:

.rectangle {
width: 200px;
height: 100px;
border: 10px solid #83B692;
background-color: #BEE7B8;
margin: 100px;
transform: rotate(37deg);
}

Set a value of 37degfor the rotate ()function, telling the element .rectangleto rotate around the rotation origin (which can be set through the transform-originproperty) by 37deg. The final effect of rotating this .rectangleelement is shown in the following figure:

Do you feel a little strange seeing such a rotation result? The effect of rotating at 37degrees should be like this, right?

The effect we see in browsers is almost the opposite. The reason is related to the direction of rotation defined on the Web. In reality, the angle value increases counterclockwise (mentioned earlier). On the Web, the angle value increases clockwise.

This may seem a bit strange, but it’s the truth, and we can’t change it. All we have to do is remember these differences and make corresponding adjustments when actually using them .

As for the angle values used in rotation in CSS, that’s about it. But one thing to remember, as we introduced before, if the angle value is less than 0 or greater than 360 degrees, it will eventually normalize to the range of 0 to 360 degrees . In most cases, negative values and values greater than 360degrees are not very important. The following figure illustrates well that negative values and values greater than 360degrees do not affect the final rotation result of the element:

As shown in the above figure, the .rectangleelement rotates 37deg, 397deg, 757degor -323deg, and the final result will be the same.

Only when we are making animations, the result is not the same . During the animation production process, the final value of the rotation angle and how to obtain the final rotation angle value are both very important. This is a detail issue in making animations. For negative values, it means that our element is rotating counterclockwise, rotating to the maximum angle value; greater than 360degmeans that the element has been rotating until the final angle value. When we truly visualize everything that actually happens, everything done in this way becomes meaningful.

The effect of the figure below is another version of the rotation of the four rectangles. Starting from 0degrees and continuing to the final values ( 37, 397, 757and -323degrees):

There is nothing special about the rectangular animation that rotates 37degbecause it is a normal effect. For the rectangle that rotates 397deg, its final stop point is also at the position of 37deg, except that the rectangle has done a complete (circular) rotation and then continues to rotate 37deg( 360 + 37); 757deg. Similarly, the final stop position of the animation is also 37deg, but after doing two rotations, it continues to rotate 37degrees ( 360 + 360 + 37); the final rotation is -323deg. The rectangle is a bit different, it rotates counterclockwise, but the final stop position of the animation is the same as other rectangles, at the 37degposition. Therefore, the final stop position of these four rectangular animations is the same, but how the animation reaches the stop point is completely different.

In addition, the duration of this animation is 8s( animation-duration: 8s), which means that the time it takes for the four rectangles to complete the animation is 8s. So the problem is that the four rectangles rotate at different angles (as mentioned earlier, some rotate more than one circle, some rotate more than two circles), but the animation duration is the same (all 8s), and they all reach the same destination (all at 37degposition), which will cause differences in the speed of rectangular rotation. As seen in the example, the effect is the same.

If you are interested in web animation production, you can move to read “ Web Animation Journey “, it is a series of tutorials about web animation production!

Above, we mainly discussed how the rotation angle works in CSS, especially the details of the difference between the rotation angle value in animation and usual. Next, we will switch to another topic and continue discussing degrees (angle values) in the web.

CSS angles in gradual change

Another typical property of angle that is also used in CSS is the related property of CSS gradual change . For example, the linear gradual change property linear-gradient ():

background: linear-gradient(45deg, #f36, #389);

The 45degin the above code refers to the angle of gradual change. Many colleagues may mistakenly think that the angle in gradual change and the angle of rotation should be the same thing. In fact, they are not the same. If you have used image editing software like Photoshop, you may find some answers:

From the above picture, it can be seen that the angle of gradual change and the angle of rotation are completely different. The angle of linear gradual change diverges from the center of the circle. Let’s take a look at a picture first.

Point Cis the center point of the gradual change container (i.e., the center point of the element), and point Ais the angle between the vertical line passing through point Cand the gradual change line passing through point C. This angle is called the gradual change angle (such as 45degin the example). This angle can be defined in the gradual change property of CSS in the following two ways:

  • Keywords: to top, to bottom, to left, to right, to top right, to top left, to bottom rightand to bottom left
  • Use unit numbers to define angles, such as 45deg, 1turn, etc. (we will talk about the relationship between degand turnlater)

If the angle value is omitted, the default is to bottom(corresponding to 180degor .5turn):

In the example above, the gradual change angle is not set, and the whiteto redgradual change color is from topto bottomgradual change, which is the same effect as using the keyword to bottom, as shown below:

In addition to using these keywords, you can also use explicit angle values, such as 45deg, and it is recommended that you use angle values instead of keywords. The following figure can help us see how the gradual change line moves when the angle changes dynamically:

Looking back at the gradual change perspective:

  • The angle is the angle between the gradual change line and the vertical line upward from the center point of the gradual change container
  • 0Degmeans to top
  • The default value of the angle (that is, the angle is not set), its value is to bottom, also the same as 180deg
  • Vertex keywords are related to the gradual change of container size

In fact, CSS gradual change is a complex knowledge system, which has a lot of unknown side, if you want to understand these potential pitfalls, please move to read the “ defensive CSS intensive “ in the “ you do not know the CSS gradual change “!

Angle in Canvas

As we all know, canvascan be used to help us draw some geometric shapes, and it can also help us do many things that CSS cannot do. Angles are also used in some APIs of canvas, such as using arc (), arcTo ()to draw circles and arcs and the rotate ()method in Canvas.

In Canvas, the measurement of angles is different from the common angle measurement, as shown in the following figure.

However, in Canvas, the angle is not the angle we usually understand, but is represented by radians. For example, if a circle is 360degrees, then represented by radians, it corresponds to radians, that is, starting and ending radians are calculated with the center of the circle as the coordinate origin. Clockwise or counterclockwise is the direction of drawing the line (or rotation direction), as shown in the figure below:

For many web developers, we are more familiar with the degree to express the angle, so to use the degree in the canvas, it is necessary to do a conversion process, the degree into radians. However, about the degree to radian, we will briefly introduce it later.

Angle in HSL

In CSS, we have multiple ways to specify colors , the most classic are hexadecimal and RGBformats. In addition, we can also use another format to specify colors, namely HSL. Among them, HSLis the first letter of the three words of hue ( Hue), saturation ( Saturation) and brightness ( Lightness).

Details related to HSLare beyond the scope of this article, but the HSL and HSV articles on Wiki Lingo explain its working principle and purpose very well. What we know is that in the Web, any color in the HSLformat can be specified through the hslor hsla function. These two numbers are similar, the only difference is that hslaadds support for transparency. For example, we can use hslato specify colors like this:

background-color: hsla(54, 100%, 62%, 1);

The above uses hslato specify the value of background-color, and the above code hsla (54,100%, 62%, 1)is a yellow-orange color.

At this point, you may be wondering. We are talking about angles in the Web, so how can we talk about colors in the Web? In other words, what is the relationship between HSL format specifying colors and using degrees? If you really think so, then you are right and should ask. HSLcolors (and extensions of the hslafunction) are composed of four values: hue , saturation , brightness and transparency .

The Hin HSL, which is the hue of a color, specifies the hue in degrees, which are mapped to the colors on the palette , as shown in the figure below:

In our example, the hue value of the specified color is 54degrees. The corresponding position on the color wheel is the yellow-orange color we see. In actual use, if we cannot determine the color on the color wheel corresponding to the angle value at the moment, we can use browser developer tools to help us, such as the following:

If you want to learn more about CSS color-related knowledge, it is recommended that you read the following tutorials:

Other degree units

In fact, in addition to angle units, we also have percentiles ( grad), radians ( rad) and turns ( turn) units:

  • Percentile ( grads ) : a scale, or percentage relative to 1/400of a whole circle, like an angle unit, supports negative values, negative values indicate counterclockwise direction, where 100 gradis equivalent to 90 deg
  • Radians ( rad) : In the Canvas section, 1radis equal to 180/πdegrees (about 57.3deg), and 1.570796326794897radis equivalent to 100grador 90deg
  • Number of turns ( turn) : 1turnis equal to 360deg

Conversion between radians and degrees

Earlier, we used angle values in CSS mostly in degrees ( deg) as the unit value, in fact, you can also use radians radas the unit value in JavaScript.

As we all know. The curvature of a complete circle is , so 2π rad = 360 °, 1π rad = 180 °, 1 ° = π/180 rad, 1 rad = 180 °/π(about 57.29577951 °). Angle expressed in degrees, multiply the number by π/180to convert it into radians; angle expressed in radians, multiply by 180/πto convert it into degrees.

rad = (π / 180) * deg

The same:

deg = (rad * 180) / π

The various curvatures we often see are as follows:

The above briefly introduced the relationship between degrees and radians. In fact, in JavaScript, we can easily implement the exchange between degrees and radians.

rad = (Math.PI * deg) / 180

The same:

deg = (rad * 180) / Math.PI

For ease of calculation and use, it can be encapsulated as a JavaScript function.

function getRads (degrees) {
return (Math.PI * degrees) / 180;
}
function getDegrees (rads) {
return (rads * 180) / Math.PI;
}

For example, if we want to convert 30degto rad, we can directly use:

getRads(30);                    // => 0.5235987755982988rad
getDegrees(0.7853981633974483); // => 45deg

The following figure shows the conversion between common angles and radians.

Percentage unit

The percentage %unit in CSS is also an important and commonly used unit. Similar to pxand em, properties that accept < length >values in CSS can use the %unit. However, its meaning will vary greatly in different usage scenarios. Therefore, to understand the %unit, the key point is: The percentage must have its corresponding reference value , that is, the percentage value is a relative value. Whenever we want to analyze its calculated value, we need to find its reference value correctly .

The implication is that the final calculated value of a single percentage value in CSS is variable. The common ones can be divided into the following categories:

Percentage in positioning

The top, right, bottom, and leftthat control positionin CSS can all use percentages as units. If their values are percentages, their corresponding reference is the widthor heightcalculation in the same direction as the containing block (but not necessarily its parent container).

As mentioned earlier, the reference object in the positioning attribute: The containing block is not necessarily its parent container . Why is that? Because in CSS, the corresponding attribute value of positionis different, and its corresponding containing block will also be different:

  • If the element is staticor relative, the containing block is usually its parent container
  • If the element is absolute, the containing block should be the ancestor element with the nearest positionof absolute, relative, or fixed
  • If the element is fixed, the containing block is the viewport.

Percentage in the box model

The properties corresponding to the box model in CSS are mainly height, min/max-height, width, min/max-height, padding, marginand border. Different properties have different reference objects.

  • Height, min/max-heightproperties are calculated relative to the heightof the containing block when the value is a percentage
  • Width, min/max-widthproperties are calculated relative to the widthof the containing block when the value is a percentage
  • Paddingand marginare relatively more complex. If the writing mode is horizontal, it is calculated relative to the widthof the containing block; if the writing mode is vertical, it is calculated relative to the heightof the containing block

Percentage in text

Common properties that control text in CSS include font-size, line-height, text-indent, vertical-align, etc. The reference objects of different properties are also different:

  • Font-sizeis calculated based on the font-sizeof the parent element
  • Text-alignand paddingare somewhat similar and have a certain relationship with the writing mode. If the writing mode is horizontal, it is calculated relative to width, and if it is vertical, it is calculated relative to height
  • Line-heightis based on font-sizecalculation
  • Vertical-alginis based on line-heightcalculation

Percentages in borders and rounded corners

The border-widthproperty in CSS does not support% units, but percentages can be used for border-radiusand border-image-widthproperties. If percentage units are used in border-radius, the radius of the rounded corner is calculated as a percentage, that is: The horizontal radius is calculated relative to the element width, and the vertical radius is calculated relative to the element height. For example:

.circle{
width: 200px;
height: 200px;
border-radius:50%;
}
.ellipse {
width: 200px;
height: 100px;
border-radius: 50%;
}

The corresponding result of the above code is shown in the following figure.

It can be seen from the result that the widthand heightof .circleare both 200px. When the border-radius: 50%, the calculated value is 100px; while .ellipseelement's widthand heightare 200pxand 100px, respectively. When the border-radiusis 50%, the calculated result is equivalent to border-radius: 100px/50px(horizontal direction relative to widthcalculation, vertical direction relative to heightcalculation).

For border-image-width, it is relatively simple. If the value of this property is a percentage, its calculation is based on the size of the image border area (including borderand padding).

For a more detailed introduction to border-radius, you can read " The border-radius you don't know "!

Percentage in background attributes

In the background property, background-size, background-originand background-positionproperties can all use percentages as units. Background-sizeis calculated based on the size of the background-originarea. The background image can be scaled.

Percentages in background-positionare more complex and need to be calculated using some mathematical formulas:

(容器尺寸 - 背景图像尺寸)* 百分比值

When the background-sizeis not reset (i.e. 100% 100%), the horizontal percentage is equal to the container width percentage minus the background image width percentage. The vertical percentage is equal to the container height percentage minus the background image height percentage.

Assuming there is an element with widthof 410px, heightof 210px, and the size of the background image used is 100px * 100px. If the value of background-positionis 75% 50%, then the final calculated value of the percentage is:

  • Horizontal position ( x-axis): (410 - 100) * 75% = 232.5px
  • Vertical position ( y-axis): (210 - 100) * 50% = 55px

If your background image is drawn using the gradual change attribute, then the position of each color in the gradual change can also be set using a percentage. The calculation for this part is relatively more detailed, so I won’t go into too much detail here. The detailed introduction will be introduced in the gradual change section. This only provides a simple example.

background-image: linear-gradient(80deg, red, blue, red, blue, red)

If the position of the color on the gradual change line is not explicitly specified, it will be left to the browser to determine the position of the color on the gradual change line. In the simplest case, there are only two colors, color 1will be placed at the gradual change line 0%position (the starting position of the gradual change line), and color 2will be placed at the 100%position (the end point of the gradual change line). If there are three colors, then color 1is at 0%of the gradual change line, color 2is at 50%of the gradual change line, and color 3is at 100%. In the example above, there are five colors, and their positions are at 0%, 25%, 50%, 75%, and 100%. They will evenly distribute the gradual change colors along the gradual change line.

The percentage in gradual change is calculated relative to the gradual change line .

Percentage in transformation

The translateand transform-originvalues in the transformproperty in CSS can also be set as percentages.

  • The percentage of translateX ()relative to the element's widthcalculation
  • The percentage of translateY ()relative to the element's heightis calculated
  • Transform-origincalculates the abscissa ( x) relative to the container's width; the ordinate ( y) relative to the container's height

Note that in translatethere is also a z-axis function translateZ (). It does not accept values in percentages.

Inheritance of percentage values

Please note that when percentage values are used for inheritable properties, only the absolute value calculated in conjunction with the reference value will be inherited, not the percentage value itself . For example, if the font-sizeof an element is 14pxand the line-height: 150%;is defined, then the line-heightinherited by the next child element of the element is 21px, which is no longer related to the child element's own font-size.

Unit of time

There are two common time units in CSS, seconds ( s) and milliseconds ( ms). 1s = 1000ms. These two units are commonly used in the CSS properties transition-duration, transition-delay, animation-durationand animation-delay.

Frequency unit

Frequency values are used in listening (or speaking) cascading style sheets and have two unit values, hertz ( Hz) and kilohertz ( kHz), with a feeling of milliseconds and seconds. Frequency can be used to change the tone of a speech reading text. Low frequencies are bass, high frequencies, and treble. For example, the following code:

.low {
pitch: 105Hz;
}
.squeal {
pitch: 135Hz;
}

Summary

In CSS, besides the units mentioned above, there are actually many other CSS units. Here we only introduce some common or commonly used CSS units. Whether it is relative units, absolute units, or time and angle units, we should choose suitable units according to our own business scenarios. For example, for mobile end adaptation, you can choose window units for adaptation, and if you expand the module size, you can use emfor more suitability. For other CSS units, if you are interested, you can try them one by one.

--

--

w3cplus
w3cplus

Written by w3cplus

Author of "Modern CSS," "Modern Web Layout," "In-Depth CSS Defense," and "A Journey into Web Animation!"