An overview of the

There are many knowledge points related to the CSS, you can refer to this article. The main selection parts of this article are common for sorting out, and refer to CSS2.2 in sequence.

The length of the unit

It can be divided into relative length units and absolute length units.

Relative length

Unit of relative length Unit of relative font length

  • Em A multiple of the current element’s calculated value
  • Ex The height of the current element x
  • Ch The height or width of the current element digit 0, usually the width of 0, i.e. 0.5em
  • The multiple of the calculated value of the REM root element (or HTML element in HTML documents) attribute

A unit of length relative to the viewport

  • vw
  • vh
  • Vmin and vmax

Vw and rem

Rem and VW implement the same idea, both of which are the proportion of a reference value, but the latter is supported by the browser native, and the former needs to set the corresponding HTML FONT size.

Maintain element aspect ratio

  1. For an image that has its own bandwidth ratio, or the aspect ratio set by aspect-ratio, set one width and one height, and the other auto will do
  2. Set the height in vw
  3. The third way is to set the padding of ::before and ::after as percentages. These two pseudo-elements generate the first and last child elements of the current element. The percentage base is the width of the containing block (the current element).
Aspect-ratio -box::before {float: left; float: left; float: left; padding-top: calc(9 / 16 * 100%); content: ''; } // if the parent element is empty, the width is 0} // if the parent element is empty, the parent element is empty. .aspect-ratio-box::after { display: block; content: ''; clear: both; } .aspect-ratio-box { max-width: 500px; background: red; }Copy the code

The length of the absolute

Absolute lengths are mostly not used for displays, just to mention px.

Less important history

At first, the conversion between pixels and other physical units is not fixed. Physical units are subject to the actual measured size, and pixels will constantly change to match the reference pixel. The latter refers to the Angle of view of a 96dpi device 1px away from an arm, which is usually 71cm long. That’s about 0.0213 degrees. So 1px is 1/96 inch at arm’s length and 1px at other distances.

However, due to historical reasons, px in a large number of contents is converted based on the assumption that the distance of one arm is 96dpi, so this conversion is fixed, namely

1in = 96px
Copy the code

Dpi and ppi

Dpi and PPI, two similar concepts, represent the density of the smallest display unit of a printing device and a screen device respectively. Ppi can also be used to represent the pixel density of a digital picture or video.

  • Dpi is the number of dots per inch
  • Ppi stands for Pixels per inch

Screen resolution refers to the total number of pixels. A 1080p screen usually has 1,920 by 1,080 pixels, which is the maximum resolution that can be adjusted. If the hardware does not change, turn down the resolution, the picture is enlarged.

Device pixels and CSS pixels

The pixel in PPI refers to the device pixel, which is the attribute of the device. CSS pixel is the pixel specified by the code. Window.devicepixelratio can obtain that each CSS pixel of the current device can be composed of several device pixels.

So theoretically we can set the length to be less than 1px when the DPR is greater than 1, which is the 1px border problem.

1px border problem

For specific solutions, please refer to this article.

Ideas including

  • Pseudo-elements are used to simulate the border, and then scale twice and then shrink twice. The border width remains the same when scale is enlarged.
  • A dynamic viewPort can be enlarged by DPR by changing the zoom ratio to 1/ DPR. For example, a screen with a width of 375px and a DPR of 2 is enlarged to 750px, but the actual screen width remains the same, so a CSS pixel is equivalent to a device pixel.

Function of symbols

Calc (), attr(), attr(

//css
p:before {
    content:attr(data-foo);
}

//html
<p data-foo="hello">world</p>
Copy the code

The selector

A selector is a pattern matching rule that determines which elements in the DOM tree the current style applies to.

There are several types of selectors

Simple selector

  • A type selector, such as div
  • Universal selector *
  • Attribute selectors, such as [attr] for elements that have attr attributes
  • Class selector. ClassName
  • Id selector # ID

pseudo-classes

Used to specify the specific state of an element, consisting of a colon (:) + pseudo-class name

  • Dynamic pseudo class
    • Link pseudo-classes, such as :link
    • User Action pseudo class, such as focus
  • Target pseudo-class, :target, the element matched when the link represented by the anchor is clicked (the anchor matches the corresponding ID)
  • Pseudo-classes, language: lang (C) is equivalent to attribute selectors [lang | = C]
  • UI state pseudo class
    • : enabled and disabled
    • :checked
  • Structure pseudo-class, such as the number of child elements, the number of mu total type of elements, or take not

Pseudo elements

Used to specify part of the selection element, consisting of two colons (::) + pseudo-element names.

  • ::first-line The first line, used for block-level element
  • ::first-letter The first letter of a block-level element
  • ::before and ::after are used to generate the first and last child elements within the element

combination

  • Offspring E F
  • Father and son E > F
  • Brothers, including the next brother in Math + P, all brothers after H1 ~ pre

The weight

The weights are calculated as follows

  • Call the ID selector a
  • Class, property, and pseudo-class selectors are denoted as b
  • Denote type selectors and pseudo-elements as C
  • Ignore the universal selector

Then combine the three numbers into a single number a-B-C to calculate the weight

Not is not weighted

Processing of element attribute values

When the user agent parses and builds the DOM tree, each attribute of each element in it needs to be assigned to provide for the final display.

The process is divided into six steps

Filtering

The first step is collecting, first finding all the declarations applied to each element, because each element may be declared 0 or more times for an attribute. Therefore, each element will have a list of declared values for each attribute

Cascading

In the second step, the cascaded value is selected based on the priority of the non-empty list.

Priority rules fall into three categories, which are sorted in order

The first category is based on the source of the statement and whether it has! Important, descending order as follows

  • Transition declarations
  • Important user agent declarations
  • Important user declarations
  • Important author declarations
  • Animation declarations
  • Normal author declarations
  • Normal user declarations
  • Normal user agent declarations

The second type is weights, where inline styles are the highest and others are sorted by selector weights

The third category is in the order in which it appears.

Defaulting

After the first two steps, each declared style will have a value, and after the third step, a specified value will be guaranteed for each attribute of each element.

There are explicit and implicit cases

Explicit processing allows you to assign the following keywords to an attribute

  • Initial, the CSS Spec specifies an initial value for each attribute
  • Inherit computed Value of the parent style
  • Unset If the corresponding property is an inheritable property, it is inherit; otherwise, it is initial, which is used to clear the declared value

If there is no explicit processing, the parent’s computed value is first inherited from the inheritable attribute, where the inherited value of the root element is initial. Initial if it is an uninheritable property.

Computing

This step absolutes each specified value to a Computed Values, including

  • Multiply the relative length by the reference value
  • Specific keywords, such as small, are calculated by definition
  • The percentage
  • Relative paths

Using

This step continues the absolutization of attributes that were not handled in the previous step, such as width: Auto, which requires the ancestor element to be computed after the previous step.

This step generates a Used value, and there is no Used value if an attribute is not applied to an element, such as an element in a non-Flex layout that has no Flex Used value.

Adjusting

The value generated in the previous step should work in principle, but the user agent may go further, such as rounding for browsers that do not support decimal length.

example

These are the complete six steps, and examples can be found here

Media queries

Media query is a test method that determines whether the current device applies to the specified media type and characteristics.

If more than one style is matched, it is processed by the Cascade of the previous section.

Application scenarios

Media queries can be used in

  • One or more specific styles in a stylesheet
  • The @import or link element introduces the stylesheet

The specific grammar

The syntax of a media query can be understood as an expression that returns Boolean, and multiple individual expressions can be combined to form the final expression.

You can check whether the media type and feature match the current device.

Media types include all,print, and Screen.

Media characteristics are used to verify various characteristics of a device in more detail, such as the width and height of the viewport is a certain value or a certain range.

The concatenation priority is from high to low

  • And with the
  • Not the
  • Or,

Only is used for compatibility and is rarely used

example

In the first scenario, it starts with @media, for example

@media (400px <= width <= 700px) {... }Copy the code

Apply the style only if the viewport is in the specified range

Second scene

@import "print-styles.css" print;
Copy the code
<link media="screen and (color), projection and (color)"
      rel="stylesheet" href="example.css">
Copy the code

Only if the conditions are met will the corresponding style sheet be introduced

The box model

The box Model is used to describe the rectangular box generated by the element in the document.

The padding and margin

Padding cannot be negative. Margin can be negative, and the upper and lower margins of non-replaceable elements in the line are invalid.

Collapsing margins

Adjacent margins of two or more Boxs in the CSS (which can be of the same class or not) can be collapsed into a single margin, and collapsed margins are collapsed.

When two or more margins are folded, the final margin width is the largest of the folded margins; If there is a negative margin, it is the width of the maximum positive margin minus the maximum negative margin absolute value; If there is no positive margin, subtract the margin with the largest absolute value from 0.

Why does it fold

This problem has been mentioned in Section 4.1.1 of CSS1, that is, by folding the vertical margin, it can be visually better and more in line with the design expectation. In 1996, when CSS1 was released, most of the site was mainly blocks of text. If margin folding did not exist, the following documents would be uneven

headings, with margin: 10px paragraphs, with margin: 5px figures, with margin: 10px

Conditions for merging two adjacent boxes

  • Are in-flow block-level boxes that participate in the same BFC
  • No inline box, clearance, Paading, or border separates them
  • Both are vertically adjacent boxes, as in the following case
    • The upper margin of a box and the upper margin of the first child element in the stream
    • The lower margin of a box and the upper margin of adjacent elements in the next stream
    • The bottom margin of an element whose margin is auto and the bottom margin of the last child element in the stream
    • The upper and lower margins of a box without a new BFC, and the box has a min-height of 0, or height of auto, or no in-stream elements

To block the merger, you only need to break the above conditions.

box-sizing

Used to specify whether content-box or border-box is scoped for length, etc. The default is content-box

Visual formatting model

In the Visual Formatting Model, each element will generate zero or more Boxs according to the Box Model

This section is full of details and covers only a few common concepts.

formatting context

A formatting context is a set of boxes used for layout, commonly including BFC and IFC.

bfc

The following situations will generate a new BFC for their content

  • The floating element
  • Absolutely traveller elements, position is ‘absolute’ or ‘fixed’.
  • Block container boxes that are not block boxes (such as inline-blocks, table-cells)
  • Overflow property is not a visible block box (unless the value has been passed to viewPort)

There is also a root element, or you can use display:flow-root to create a BFC

In a BFC, boxes are arranged vertically one by one from above the containing block (the elements in the row will form anonymous block boxes), and the vertical distance between the two boxes depends on the margin attribute.

Application:

  1. Clear float
  2. Avoid margin folding

ifc

A block container box that does not contain block-level boxes creates an IFC (inline formatting Context), in which boxes are placed parallel to each other from above the container mouth. The boxes may be aligned in different ways vertically.

floating

In a float Model, a box is first laid out according to Normal Flow, then out of the document flow, and then moved as far left or right as possible.

Other content in the parent element of the floating element is placed after the floating element, such as wrapping text around the floating element.

Block level elements following the float element (inline or inline-block is invalid) can be set to clear to avoid being on the same line as the float element.

Parent collapse

Because of the separation from the document flow, if the parent element is not as tall as the floating child element, it will collapse, which is also a clear float problem.

There are two solutions

  • The first is to add a block-level child after the float element (such as using the ::after pseudo-element) and set clear:both to prop up the parent element
  • The second is to have the parent create a BFC, which will count the floating child elements toward the height

position

The position property determines the positioning scheme

  • Static default, normal flow layout, four direction attributes are not used
  • Relative to normal flow, relative to normal position
  • Absolute vs. containing Block layout.
  • Fixed layout relative to containing block.
  • Sticky is offset in four directions based on the nearest scrollable (overflow is not visible) ancestor location.

Custom attributes

:root {
  --main-color: #06c;
  --accent-color: #006;
}
/* The rest of the CSS file */
#foo h1 {
  color: var(--main-color);
}

Copy the code

Flexible Box

A Flex layout is a one-dimensional layout that contains a main axis along which flex items are arranged and elastically filled. The axis perpendicular to the principal axis is called cross

There are a few things to note about the Flex item

  • Absolutely positioned child elements do not participate in Flex layout and are not considered here
  • Margin of Flex item is not merged
  • Z-index is valid even if position is static
  • Float and vertical-align are invalid

Sequence and direction

On the Flex element

  • Flex-direction Sort by row or column, forward or backward
  • Whether flex-wrap can wrap a line, which is the opposite of wrap when wrap-reverse, changing the first line to the last line and reversing each line.
  • The flex – flow < > ‘flex – direction’ | | < > ‘flex – wrap’

In the child element order takes an integer, default 0, the smaller the first

The elastic

The flex property, used for flex-item, makes it elastic to fill the main axis of the container. The abbreviation is recommended because it will reset correctly for some common uses

abbreviations

But none value | [< > ‘flex – turns’ <‘ flex – the shrink >? | | < > ‘flex – basis’]

  • Flex-grow specifies how to stretch the corresponding item to allocate free space. If omitted, set to 1
  • If the size of an item exceeds the width of its parent element, shrink the item to 1
  • Flex-basis determines how to allocate the initial width, which is set to 0 when omitted, i.e. all controls on the spindle are free
    • Auto takes main size (the size of the main axis) as the property value, or content if the latter is also auto
    • content
    • < > ‘width’
  • None is 0, 0 auto

Several common values

  • Initial, equivalent to unspecified, equivalent to 0 1 auto, the initial value, compressed by default but not stretched
  • Auto, equivalent to 1, 1 auto, scales according to the remaining space
  • None is equal to 0, 0 auto. It’s completely inelastic
  • Equivalent to positive number 1 0, the remaining space is allocated proportionally

alignment

See the different alignment diagrams here

Aligning with auto margins

Margin-left: auto allocates all space if the main axis has free space

Alignment of the main axis

justify-content

  • The flex – start by default
  • flex-end
  • center
  • The distance between the end edges of a space-around is half the distance between elements
  • Space-between ends are bounded, and each intermediate distance is the same
  • The edge of the space- instituted is the same distance between the elements

Alignment of the cross axis

align-items

  • The flex – start by default
  • flex-end
  • center
  • baseline
  • Stretch the tensile

Align-self has one more than the previous one

  • Auto Default, determined by align-items

Alignment in cross direction when the main axis has multiple rows

align-content

  • flex-start
  • flex-end
  • center
  • space-between
  • space-around
  • stretch

Alignment of all rows as a whole when cross cannot be filled is similar to alignment in the main axis using justice-content

Grid Layout

The Flex layout can only bounce in one direction on the main axis, while the Grid implements an elastic layout in both directions, with the horizontal axis called inline and the vertical axis called block.

The aspects of item mentioned in the previous section also apply here. When margin is used, it refers to the outer border of the item in the corresponding grid, which has no effect on the grid.

Define the grid

There are explicit and implicit definitions of squares.

An explicit definition explicitly specifies the width of the corresponding row and column

  • The width of each row in the grid-template-rows grid
  • The width of each column of the grid-template-columns grid
  • Grid-template-areas are named for the squares and edges of rows and columns that intersect
  • Grid-template is a shorthand for these three attributes

If there are still squares that are not explicitly defined, you need to implicitly define them

  • grid-auto-rows
  • grid-auto-columns

There’s also a flex-direction like property

  • The grid – auto – flow value [row | column] | | dense

  • Grid is a shorthand for the above properties

Place the grid item

Now that you’ve defined the cells, place the elements from the Grid Container into them.

You can specify the location to be placed by naming the area, the area bounded by the four start lines, or specifying the start line and the number of lines.

Specify each line individually

  • grid-row-start
  • grid-column-start
  • grid-row-end
  • grid-column-end

Line of shorthand

  • grid-row
  • grid-column

The designated area

  • Grid-area can be a named area or four lines separated by slash lines grid-row-start, grid-column-start, grid-row-end, and grid-column-end

gap

You can specify an interval between each item

  • row-gap
  • column-gap
  • gap

alignment

The following reference is here

Grid layouts have finer alignment granularity than Flex layouts. The Flex layout provides the flex content as a whole, main aligned, cross aligned alignment-content, and cross aligned align-items for each item in the main axis range, as well as the corresponding align-self for individual items

On top of this, the grid layout also provides inline alignment of the entire implement-items and corresponding context-self for individual items

transition

It is generally updated immediately when an attribute of an element changes, transitioning the attribute to change within a specific duration.

Abbreviation for/none | | | < time > | | | | < time >

corresponding

  • Transition-property Specifies the CSS property to be applied. The value can be all, None, or comma-separated. The default value is all
  • Transition-duration Transitional duration in units. Default: 0
  • How to calculate the value of transition-timing-function to modify the speed of transition
  • Transition-delay Specifies the delay time. The unit is 0

Such as

.test{ height: 100px; width: 100px; background-color: pink; The transition; 2s; } .test:hover{ width: 500px; }Copy the code

Animations

Animation is generated by keyframes that animate CSS property values. The duration of these keyframes, the number of repetitions, or the repetitive behavior can be controlled

Abbreviation for < time > | | | | < time > | | | | | | | | | | [none |]

corresponding

  • Animation-duration Animation duration, expressed in units, default 0s
  • animation-timing-function
  • animation-delay
  • Animation-iteration -count The number of times an animation runs. The default is 1
  • Animation-direction Indicates whether the animation is played in reverse direction
    • Normal is always forward
    • Alternate positive and negative
    • reverse
    • alternate-reverse
  • How does animation-fill-mode apply the style to its target before and after execution
    • None Animation does not modify element styles when the animation is not executed
    • After the forward animation ends, the last frame will be preserved
    • Backwards During animation delay, animation will apply the first frame
    • Both applies both attributes
  • Single-animation-play-state Specifies whether an animation is running or paused
    • Running
    • Paused has been stopped
  • Keyframes -name Specifies the animation of the application, which is defined by @keyframes
@keyframes <keyframes-name> {  <keyframe-block-list>}
Copy the code

The points in time can be expressed as percentages, from, to, where from stands for 0 and to stands for 100%

Such as

@keyframes slidein { from { transform: translateX(0%); } to { transform: translateX(100%); }}Copy the code

transform

The bottom is the positive y direction, and the right is the positive X direction

  • Transform-box All transformations are performed relative to the reference box represented by this property. In a non-SVG environment, only border-box and Content-box are concerned
  • Transform-origin Specifies the origin of the transform coordinate system, where 0 0 represents the upper left corner of the Reference box. The default value is 50% 50%

Transform value none | conversion function which is separated by commas, for example

  • Translate () Moves the position
  • The zoom scale ()
  • Rotate the rotate ()
  • Skew ()

CSSOM

This refers to the CSS related browser API, see here

The extended API on Windows

screen

Screen – related information, mounted to screen

  • availWidth
  • availHeight
  • width
  • height
  • colorDepth
  • pixelDepth

browsing context

Move and scale the browsing context and mount it directly to the window

  • moveTo(long x, long y);
  • moveBy(long x, long y);
  • resizeTo(long width, long height);
  • resizeBy(long x, long y);

viewport

The width and height of the viewport, mounted to the WINDOs

  • innerWidth
  • innerHeight

viewport scrolling

Scroll related, mounted on window

  • ScrollX /scrollY returns the pixel value of scrolling relative to the view
  • PageXOffset /pageYOffset corresponds to the first term
  • Scroll (x-coord, y-coord)/scroll(options) to a specified position
  • scrollTo
  • scrollBy

client

Client window, mounted to the window

  • ScreenX /screenY Coordinates of the window relative to the screen
  • screenLeft/screenRight
  • outerWidth/outerHight
  • devicePixelRatio

Document

Mounted to document

  • ElementFromPoint (double x, double y) returns the uppermost element in the specified coordinate
  • ElementsFromPoint (double x, double y) Specifies the coordinates of an array of elements
  • CaretPositionFromPoint (double x, double y) returns a CaretPosition object
  • ScrollingElement returns a reference to a scrolling document element, usually an HTML element

Element interface

  • GetClientRects () returns a collection of DOMRect objects representing each CSS border box’s bounding rectangles. Most elements have a border box each, But multi-line inline elements have one for each line.
The DOMRect object represents the size and position of the rectangle, and contains properties -x /y top-left coordinates -width-height-top y+height if height is negative, otherwise y -bottom y+height if height is negative, Otherwise y+ height-right if height is negative x is responsible for x+ width-left if height is negative x+width. Otherwise for xCopy the code
  • GetBoundingClientRect () returns a corresponding DOMRect object
  • scrollIntoView(optional (boolean or ScrollIntoViewOptions) arg = {}); Scroll to visible
  • scroll();
  • scrollTo()
  • scrollBy()
  • ScrollTop /scrollLeft The distance from the top of the rolled content to the visible content
  • scrollWidth/scrollHeight; Contains the width and height of the part being rolled
  • clientTop/clientLeft
  • clientWidth/clientHeight

HTMLElement extension on the HTMLElement interface

  • offsetParent
  • offsetTop/offsetLeft
  • offsetWidth/offsetHeight

Interface on MouseEvent

Current mouse position

  • ScreenX /screenY coordinates relative to the screen
  • PageX /pageY coordinates relative to the document
  • Coordinates of clientX/clientY relative to the viewport
  • X/ y is equivalent to clientX/clientY
  • OffsetX /offsetY coordinates relative to the target element padding Edge