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 color
property 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 elementwidth
,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
,height
or defaultfont-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
,bottom
andleft
properties - 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: width
property, its value can be a percentage value, or a value with a number and a unit; color
value can be a keyword, or a function value; font-size
can be a percentage, a keyword, or a numerical value with a unit; line-height
can 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
vw
andvh
, etc - Container query relative length unit : the length relative to the size of the query container, such as
cqw
andcqh
, 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
, pc
and pt
, among which px
is the most common absolute unit. So far, px
can 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 px
is 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, px
is 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 1
CSS pixel can be changed (i.e. the relativity of the first aspect of CSS pixels); between different devices, the physical pixel represented by each 1
CSS 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 PPI
and 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 one
CSS 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.
1
reference pixel is the angle between the line of sight and the horizontal line when the output of a device with a resolution of 96DPI
is viewed from an arm's length (i.e. 1
inch 96
points), and 1
point (i.e. 1/96
inch). It is not 1/96
inch in length, but the angle between the line of sight and the horizontal line when the output of a device with a resolution of 96DPI
is one unit (i.e. 1/96
inch) from an arm's length. It is generally believed that the average human arm length is 28
inches, 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.5
to3
times longer - if you are a42
inch color TV, it is about3
meters 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 150px
in 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 DPR
is 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 2
or 3
times the size.
Although px
is 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), pc
and pt
, etc. Among them, in
, cm
and mm
can be directly converted to px
:
1in = 96px
1cm = 37.8px
1mm = 3.78px
And pc
and pt
and in
are directly related:
1in = 72pt
1in = 6pc
If you want to convert pt
and pc
directly to px
, you can use in
as a bridge. For example:
1in = 96px = 72pt
, then1px = 72/96 = 0.75pt
1in = 96px = 6pc
, then1px = 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
, 1Q
is 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
, lh
and rlh
. Among them, em
, rem
, ex
and ch
are 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 1em
is:
1em = 16px = 0.17in = 12pt = 1pc = 4.mm = 0.42cm
As we all know, every browser has a default font-size
size, and this value is usually 16px
(when the user does not modify the browser font size). This is why 1em = 16px
.
Em
Another important point is that em
is related to the font-size
of their ancestor elements. Therefore, if the font-size
of the ancestor element is set to 0.5em
, and the font-size
of its child elements is set to 1em
, the calculated font-size
in 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-size
to em
, it will increase the complexity of em
calculation and conversion, for example:
There is a certain formula for the conversion between px
and em
, as follows:
1 ÷ 父元素的font-size × 需要转换的像素值 = em值
Note that when the
font-size
of the element itself is not explicitly set, thefont-size
of 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 em
unit applies not only to the font-size
property, 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 aspx
,em
,pt
,in
, etc. As with any CSS size, there are no spaces between numbers and units. If<number>
is0
, the length unit after it is optional.
If you use em
as the unit of the <length>
value on a non- font-size
property, it will be affected by the font-size
of the element. There is a common understanding among many developers that em
units are relative to the font-size
of the parent element. But in fact? They are relative to the font-size
**of the element using the** em
unit. The font-size
of the parent element can affect the em
value, but this happens purely because of inheritance.
As mentioned earlier, when using em
units 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 ofpx
toem
.
From the previous knowledge, we know that properties using em
units are determined by the font-size
of the element. However, the element may inherit the font-size
of its parent element, and the parent element may inherit the font-size
of its parent element. Therefore, the font-size
in em
units may be affected by the font-size
of any parent element. This argument has been verified in the above example.
Since the font-size
of the element will change, the properties that use em
units 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-size
in the div
element and its ancestor elements, so the font-size
of this element inherits the browser's default font-size
, which is 16px
. Therefore, the em
in the width
, height
, border-width
and padding
properties will be calculated based on 16px
as the benchmark. Therefore, the final result is shown in the figure above. If we nest a child element div
in the div
, the result will be as follows:
Two div
using the property of em
, the final result is the same, but the child element div
overflows the parent element div
. If we explicitly set font-size: .5em
in the child element div
, the result will be another one:
In this regard, the em
unit can better maintain and expand the size of components. For example, the properties of the size of the cgroup component, such as width
, height
, padding
and border-width
, etc. When using em
as the unit, if you want to adjust the size of the component, you can directly adjust the font-size
of the component (if the element itself does not set the font-size
, you can adjust the font-size
of its ancestor elements). For example, as shown in the figure below, adjusting the font-size
can be very flexible in the size of the cgroup component:
rem
Rem
is less complex than em
, it is just the font-size
calculation relative to the root element <html>
. The W3C specification describes rem
as follows:
Font size of the root element!
Many times, we can use rem
as a substitute for em
. Especially in the use of the font-size
property, but rem
and em
have one biggest difference: any element with a value of 1rem
is 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-size
value is explicitly set in the body
, it will not affect the font-size
of its child element h3
, and the font-size
of h3
is always calculated relative to the root element <html>
.
In addition, rem
and em
are somewhat similar, and properties that can accept <length>
as a value can be in rem
units, and they are calculated relative to the font-size
of 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, orrem
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 rem
will make their components lack Modularization; other developers use rem
for 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 rem
or em
, it is rational to use rem
or em
in different places. In fact, many successful cases have also proven this point:
- If this property is measured according to its
font-size
, you should selectem
- Everything else should use
rem
Also, you can choose according to the differences between the two:
The style values computed by rem
andem
in the Client ( computed style (Computed Style) ) will be explicitlypx
rem
relative to the root elementhtml
'sfont-size
calculation,em
relative to the elementfont-size
calculationrem
can inheritfont-size
values from browser font settings,em
may be affected by any inherited parent elementfont-size
- The use of
em
should be based on thefont-size
of the component, not thefont-size
of the root element - When you don’t need to use
em
units and need to scale according to the browser'sfont-size
setting, you should userem
Ex and ch
ex
and ch
are typographical units, which means their values depend on the element's font-family
. When we use em
and rem
units, 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 ex
and ch
units provide more flexibility. They require the browser to determine the referenced font-family
before calculating the value and applying the style. Because the element's font-family
style has a direct relationship and influence on the calculation of the ex
and ch
unit values.
In typographical terms, the x
height 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-size
of the font and the x
height can tell you a lot about the proportions of the font.
The ex
unit values come from the x
height of the font context they calculate, and x
height is determined by two factors: font-family
and font-size
. In other words, they are equal to the x
height of a specific font at a specific font-size
.
As shown above, font-family
for Helvetica Neue
set the font-size
to 100px
, so 1ex
is approximately equal to 52px
.
ch
is 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 0
is usually the average character width of the font, which is an estimate, so it will be a bit bad.
Since the ch
unit 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 ch
unit.
“ 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 theex
unit on the root elementrch
: value calculation relative to thech
unit on the root elementcap
: equal to the cap-height of the first available font, which is approximately equal to the height of the capital Latin letterrcap
: Calculate the value of thecap
unit relative to the root elementlh
: equal to the line-height of the element (line-height
)rlh
: Calculated relative to the value oflh
units on the root element, when used for thefont-size
orline-height
properties of the root element, it refers to the initial values of these propertiesiC
: is the Eastern version ofch
. It is the size of the CJK (Chinese, Japanese, and Korean) ideogramwater
(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 be1em
ric
: value calculation relative to theic
unit on the root element
Window relative unit
In CSS, besides font relative units, there are also window relative units, mainly vw
, vh
, vmin
and 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 widthvh
: percentage of window heightvmin
: currently smallervw
andvh
vmax
: currently largervw
andvh
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 1vh
is 9px
. Similarly, if the display window width is 750px
, the value obtained by 1vw
is 7.5px
. vh
and vw
are always related to the height and width of the window, but vmin
and vmax
are 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 1100px
width and 700px
height, 1vmin
will be 7px
, and 1vmax
will be 11px
. However, if the width is set to 800px
and 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 vi
and vb
:
vi
: refers to the browser window internal connection axis size (inline-size
) of1%
vb
: Refers to1%
of the browser windowblock-size
Use the lv
prefix in CSS to define the units of large windows, which include lvw
, lvh
, lvi
, lvb
, lvmin
and lvmax
. Also use the sv
prefix to define the units of small windows, which include svw
, svh
, svi
, svb
, svmin
and svmax
. Dynamic window units are defined with the dv
prefix, which includes dvw
, dvh
, dvi
, dvb
, dvmin
and 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,1cqw
is equal to the query container width1%
cqh
: query height, calculated relative to the height of the query container, that is,1cqh
is equal to the height of the query container1%
cqi
: query internal connection axis size, relative to the query container internal connection axis size calculation, that is,1cqi
is equal to1%
cqb
: query block axis size, relative to the query container block axis size calculation, that is,1cqb
is equal to the query container block axis size1%
cqmin
: query the minimum value, is to query the internal connection axis sizecqi
or query the smaller value in the block axis sizecqb
cqmax
: query the maximum value, is to query the internal connection axis sizecqi
or query the larger value in the block axis sizecqb
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 0
and 360
degrees:
This doesn’t mean you can’t handle degree values outside of 0
and 360
. Negative numbers and values greater than 360
degrees are allowed. It's just that they are always classified as 0
and 360
degrees. Take a look at the following two normalized variants:
In the first variant, the value we specify is actually -90
degrees. The resulting angular path is clockwise and stops at the position of 270
degrees ( 360 - 90 = 270
). In the second variant, the value we specify is 420
degrees. This means that we have to complete a full rotation ( 360
degrees) and then continue rotating 60
degrees. In most cases, the final degree value of the first variant is 270
degrees, and the final degree value of the second variant is 60
degrees. Whether the value of the angle is negative or not is irrelevant. In order to obtain the final angle value between 0
and 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 transform
property, 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 37deg
for the rotate ()
function, telling the element .rectangle
to rotate around the rotation origin (which can be set through the transform-origin
property) by 37deg
. The final effect of rotating this .rectangle
element is shown in the following figure:
Do you feel a little strange seeing such a rotation result? The effect of rotating at 37
degrees 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 360
degrees are not very important. The following figure illustrates well that negative values and values greater than 360
degrees do not affect the final rotation result of the element:
As shown in the above figure, the .rectangle
element rotates 37deg
, 397deg
, 757deg
or -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 360deg
means 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 0
degrees and continuing to the final values ( 37
, 397
, 757
and -323
degrees):
There is nothing special about the rectangular animation that rotates 37deg
because 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 37
degrees ( 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 37deg
position. 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 37deg
position), 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 45deg
in 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 C
is the center point of the gradual change container (i.e., the center point of the element), and point A
is the angle between the vertical line passing through point C
and the gradual change line passing through point C
. This angle is called the gradual change angle (such as 45deg
in 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 right
andto bottom left
- Use unit numbers to define angles, such as
45deg
,1turn
, etc. (we will talk about the relationship betweendeg
andturn
later)
If the angle value is omitted, the default is to bottom
(corresponding to 180deg
or .5turn
):
In the example above, the gradual change angle is not set, and the white
to red
gradual change color is from top
to bottom
gradual 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
0Deg
meansto top
- The default value of the angle (that is, the angle is not set), its value is
to bottom
, also the same as180deg
- 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, canvas
can 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 360
degrees, then represented by radians, it corresponds to 2π
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 RGB
formats. In addition, we can also use another format to specify colors, namely HSL
. Among them, HSL
is the first letter of the three words of hue ( Hue
), saturation ( Saturation
) and brightness ( Lightness
).
Details related to HSL
are 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 HSL
format can be specified through the hsl
or hsla
function. These two numbers are similar, the only difference is that hsla
adds support for transparency. For example, we can use hsla
to specify colors like this:
background-color: hsla(54, 100%, 62%, 1);
The above uses hsla
to 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. HSL
colors (and extensions of the hsla
function) are composed of four values: hue , saturation , brightness and transparency .
The H
in 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 54
degrees. 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:
- Color formats in modern CSS: RGB, HSL, HWB, LAB, and LCH
- New CSS color space: set high definition colors for the web
- OKLCH and OKLAB in CSS
- Blending colors in CSS: color-mix ()
- Web control UI color customization: accent-color and color-scheme
- Color contrast: color-contrast ()
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 to1/400
of a whole circle, like an angle unit, supports negative values, negative values indicate counterclockwise direction, where100 grad
is equivalent to90 deg
- Radians (
rad
) : In the Canvas section,1rad
is equal to180/π
degrees (about57.3deg
), and1.570796326794897rad
is equivalent to100grad
or90deg
- Number of turns (
turn
) :1turn
is equal to360deg
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 rad
as the unit value in JavaScript.
As we all know. The curvature of a complete circle is 2π
, so 2π rad = 360 °
, 1π rad = 180 °
, 1 ° = π/180 rad
, 1 rad = 180 °/π
(about 57.29577951 °
). Angle expressed in degrees, multiply the number by π/180
to 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 30deg
to 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 px
and 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 left
that control position
in CSS can all use percentages as units. If their values are percentages, their corresponding reference is the width
or height
calculation 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 position
is different, and its corresponding containing block will also be different:
- If the element is
static
orrelative
, the containing block is usually its parent container - If the element is
absolute
, the containing block should be the ancestor element with the nearestposition
ofabsolute
,relative
, orfixed
- If the element is
fixed
, the containing block is theviewport
.
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
, margin
and border
. Different properties have different reference objects.
Height, min/max-height
properties are calculated relative to theheight
of the containing block when the value is a percentageWidth, min/max-width
properties are calculated relative to thewidth
of the containing block when the value is a percentagePadding
andmargin
are relatively more complex. If the writing mode is horizontal, it is calculated relative to thewidth
of the containing block; if the writing mode is vertical, it is calculated relative to theheight
of 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-size
is calculated based on thefont-size
of the parent elementText-align
andpadding
are somewhat similar and have a certain relationship with the writing mode. If the writing mode is horizontal, it is calculated relative towidth
, and if it is vertical, it is calculated relative toheight
Line-height
is based onfont-size
calculationVertical-algin
is based online-height
calculation
Percentages in borders and rounded corners
The border-width
property in CSS does not support% units, but percentages can be used for border-radius
and border-image-width
properties. 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 width
and height
of .circle
are both 200px
. When the border-radius: 50%
, the calculated value is 100px
; while .ellipse
element's width
and height
are 200px
and 100px
, respectively. When the border-radius
is 50%
, the calculated result is equivalent to border-radius: 100px/50px
(horizontal direction relative to width
calculation, vertical direction relative to height
calculation).
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 border
and 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-origin
and background-position
properties can all use percentages as units. Background-size
is calculated based on the size of the background-origin
area. The background image can be scaled.
Percentages in background-position
are more complex and need to be calculated using some mathematical formulas:
(容器尺寸 - 背景图像尺寸)* 百分比值
When the background-size
is 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 width
of 410px
, height
of 210px
, and the size of the background image used is 100px * 100px
. If the value of background-position
is 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 1
will be placed at the gradual change line 0%
position (the starting position of the gradual change line), and color 2
will be placed at the 100%
position (the end point of the gradual change line). If there are three colors, then color 1
is at 0%
of the gradual change line, color 2
is at 50%
of the gradual change line, and color 3
is 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 translate
and transform-origin
values in the transform
property in CSS can also be set as percentages.
The percentage of translateX ()
relative to the element'swidth
calculationThe percentage of translateY ()
relative to the element'sheight
is calculatedTransform-origin
calculates the abscissa (x
) relative to the container'swidth
; the ordinate (y
) relative to the container'sheight
Note that in
translate
there is also az
-axis functiontranslateZ ()
. 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-size
of an element is 14px
and the line-height: 150%;
is defined, then the line-height
inherited 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-duration
and 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 em
for more suitability. For other CSS units, if you are interested, you can try them one by one.