Bull pen! Byte beating boss sorting: CSS core knowledge (10000 word long text, worth collecting!)

Time:2022-2-3

This article focuses on the core knowledge of CSS and the common requirements in the project. Although the writing is too long, it is relatively basic and suitable for primary, intermediate and front-end reading. Please skip the part you have mastered when reading.

This article has been written off and on for a long time, and has also referred to many excellent articles, but perhaps there are still bad or wrong places in the article. Please give more advice and directly mention it in the comments.

Little tip: the follow-up content is more wonderful.

Core concepts and knowledge points

grammar

The core function of CSS is to set CSS properties to specific values. A key value pair of attributes and values is calledstatement(declaration)。

color: red;
Copy code

And if you use one or more declarations{}When wrapped, it forms aDeclaration block(declaration block)。

{
    color: red;
    text-align: center;
}
Copy code

If the declaration block needs to act on the corresponding HTML element, it also needs to addselector。 The selector and the sounder block formCSS rule set(CSS ruleset), often referred to as CSS rules.

span {
    color: red;
    text-align: center;
}
Copy code

The semicolon can be omitted from the last declaration in the rule set, but it is not recommended because it is error prone.

In CSSnotes

/*Single line note*/

/*
    Multiline
    notes
*/
Copy code

In the CSS file, in addition to comments, CSS rule sets and @ rules, some other things defined will be ignored by the browser.

@Rules

CSS rules are the main body of style sheets, which usually include a large number of rule lists. But sometimes you need to include other information in the style sheet, such as character set, importing other external style sheets, fonts, etc., which need special statement representation.

The @ rule is such a statement. CSS contains the following @ rules:

  • @namespaceTells CSS engines that XML namespaces must be considered.
  • @media, if the media query conditions are met, the rules in the condition rule group will take effect.
  • @page, describe the change of layout when printing the document
  • @font-face, describing the external fonts that will be downloaded.
  • @keyframes, describe the key frames of CSS animation.
  • @document, if the document style sheet meets the given conditions, the rules in the condition rule group take effect. (extended to CSS level 4 specification)

In addition to the above, the following will also introduce some more astringent @ rules.

@charset

@charsetDefines the character set used by the style sheet. It must be the first element in the style sheet. If there are multiple@charsetIt is declared that only the first one will be used and cannot be used in HTML elements or HTML pages<style>Element.

Note: the value must be enclosed in double quotation marks, and

@charset "UTF-8";
Copy code

Usually, no @ charset rule is written in the style file. What character code is used in this CSS file?

What character encoding is used in a style sheet file? The browser has a set of recognition order (priority from high to low):

  • At the beginning of the fileByte order markCharacter value, but the general editor cannot see the BOM value in the file header;

  • In the HTTP response headercontent-typeField containscharsetThe specified value, such as:

    Content-Type: text/css; charset=utf-8
    Copy code
  • The character code specified in the @ charset rule defined in the CSS file header;

  • <link>Charset attribute in tag, which has been abolished in HTML5;

  • Default isUTF-8

@import

@importUsed to tell the CSS engine to introduce an external style sheet.

Link and @ import can import a style file. What’s the difference between them?

  • Link is an HTML tag. In addition to importing CSS, it can also import other resources, such as pictures, scripts and fonts; While @ import is the syntax of CSS and can only be used to import CSS;
  • Link imported styles will be loaded at the same time when the page is loaded, @ import imported styles need to be loaded after the page is loaded;
  • Link has no compatibility problem, @ import is not compatible with IE5 or below;
  • Link can dynamically introduce a stylesheet into DOM through JS operation to change the style, but @ import cannot.

@supports

@supportsIt is used to query whether a specific CSS is effective. It can be combined with not, and and or operators for subsequent operations.

/*If custom attributes are supported, set the body color to the color specified by the variable Varname*/
@supports (--foo: green) {
    body {
        color: var(--varName);
    }
}
Copy code

Lamination

Cascading style sheet, how to understand the cascading here? In fact, it is one of the core features in CSS, an algorithm for merging attribute values from multiple sources. For example, when there are many CSS declarations for an HTML tag, who should work in the end? That’s what cascade is about.

The styles of different sources will be stacked in the following order. The lower the priority, the higher the priority:

  • Declarations in the user agent style sheet (for example, the default style of the browser, which is used when no other styles are set).
  • General declaration in user style sheet (custom style set by user. Since chrome gave up the function of user style sheet very early, its sorting will not be considered here.)
  • General declarations in the author’s style sheet (these are the styles set by our web developers).
  • Author style sheet! Important statement.
  • In the user style sheet! Important statement s

To understand cascading, you need to combine the priority and inheritance of CSS selectors. For example, for the same selector, the declaration defined later will overwrite the previous one; The style defined by the author takes precedence over the style inherited by default.

selector

CSS selector is undoubtedly one of its cores. You must master the basic selector and some common pseudo classes. Common selectors are listed below. For more usage of selectors, seeMDN CSS Selectors

Base selector

  • Label selector:h1
  • Class selector:.checked
  • ID selector:#picker
  • Universal selector:*

attribute selectors

  • [attr]: Specifies the element of the attribute;
  • [attr=val]: the element whose attribute is equal to the specified value;
  • [attr*=val]: the element whose attribute contains the specified value;
  • [attr^=val]Attribute: the element whose attribute starts with the specified value;
  • [attr$=val]: the element whose attribute ends with the specified value;
  • [attr~=val]Attribute: the element whose attribute contains the specified value (complete word) (not recommended);
  • [attr|=val]Attribute: the element whose attribute begins with the specified value (full word) (not recommended);

Selector combination

  • Adjacent brother selector:A + B
  • Normal brother selector:A ~ B
  • Sub selector:A > B
  • Descendant selector:A B

Pseudo class

Conditional pseudo class

  • :lang(): match page elements based on element language;
  • :dir(): elements that match the writing direction of a specific text;
  • :has(): matches the element containing the specified element;
  • :is(): matches the elements in the specified selector list;
  • :not(): used to match elements that do not match a set of selectors;

Behavior pseudo class

  • :active: elements activated by the mouse;
  • :hover: elements suspended by the mouse;
  • ::selection: the element selected by the mouse;

State pseudo class

  • :target: the element of the current anchor;
  • :link: link elements not accessed;
  • :visited: the link element that has been accessed;
  • :focus: enter the focused form element;
  • :required: enter required form elements;
  • :valid: enter legal form elements;
  • :invalid: enter illegal form elements;
  • :in-range: enter form elements within the range;
  • :out-of-range: enter form elements outside the scope;
  • :checked: the selected form element;
  • :optionalOptions: optional form elements;
  • :enabled: form elements enabled by events;
  • :disabledEvent: disabled form element;
  • :read-only: read only form elements;
  • :read-write: readable and writable form elements;
  • :blank: enter a blank form element;
  • :current(): browse for elements in;
  • :past(): browsed elements;
  • :future(): elements not browsed;

Structural pseudo class

  • :root: the root element of the document;
  • :empty: elements without child elements;
  • :first-letter: the initial of the element;
  • :first-line: the first line of the element;
  • :nth-child(n): the element with the specified order index in the element;
  • :nth-last-child(n): elements with reverse index specified in the element;;
  • :first-child: the first element in the element;
  • :last-child: the element with tail in the element;
  • :only-childParent element: only the element of this element;
  • :nth-of-type(n): the label that specifies the order index in the label;
  • :nth-last-of-type(n): the label in which the reverse index is specified in the label;
  • :first-of-type: the first label in the label;
  • :last-of-type: tail label in the label;
  • :only-of-type: the parent element has only the label of this label;

Pseudo element

  • ::before: insert content before element;
  • ::after: insert content after element;

priority

Priority is a weight assigned to a specified CSS declaration, which is determined by the value of each selector type in the matched selector. In order to remember, the weight can be divided into the following levels. The larger the value, the higher the weight:

  • 10000:!important;
  • 01000: inline style;
  • 00100: ID selector;
  • 00010: class selector, pseudo class selector and attribute selector;
  • 00001: element selector, pseudo element selector;
  • 00000: universal selector, descendant selector and brother selector;

You can see that the inline style (the style defined by the style attribute in the element) takes precedence over any selector; And add!importantYou can also raise the priority to the highest, because it has the highest priority, so you need to use it carefully. Here are some precautions:

  • Be sure to give priority to using the priority of style rules to solve problems instead of! important;
  • It can only be used in specific pages that need to cover the whole site or external CSS! important;
  • Never use it in your plugin! important;
  • Never use in site wide CSS code! important;

Inheritance

A very important attribute in CSS is the value of the inherited parent element. For example, the text color of the page root element html is black by default, and all other elements in the page will inherit this color. When the following style is declared, the H1 text will turn orange.

body {
    color: orange;
}
h1 {
    color: inherit;
}
Copy code

Imagine that if there is no inheritance in CSS, we need to set color for labels of different text. As a result, the file size of CSS will increase infinitely.

There are many CSS attributes, but not all attributes can inherit the corresponding attributes of the parent element by default. Which attributes have the behavior of default inheritance? The attributes that will not affect the page layout can be divided into the following categories:

  • Font related:font-familyfont-stylefont-sizefont-weightEtc;
  • Text related:text-aligntext-indenttext-decorationtext-shadowletter-spacingword-spacingwhite-spaceline-heightcolorEtc;
  • List related:list-stylelist-style-imagelist-style-typelist-style-positionEtc;
  • Other attributes:visibilitycursorEtc;

For other attributes that do not inherit by default, you can also control the inheritance behavior through the following attribute values:

  • inherit: inherit the calculated value of the attribute corresponding to the parent element;
  • initial: apply the default value of this attribute. For example, the default value of color is#000
  • unset: if the attribute can be inherited by default, theninheritOtherwise, the same asinitial
  • revert: equivalent tounset, poor compatibility.

Document flow

In the world of CSS, the content will be arranged and displayed from left to right and from top to bottom. Under normal circumstances, the page will be displayed line by line, and each line may be composed of multiple columns, so it visually looks from top to bottom and left to right, and this is the streaming layout in CSS, also known as document flow. Like water, document flow can adapt to its container. Generally, it has the following characteristics:

  • Block level elements will occupy the whole line by default, so multiple block level boxes are arranged from top to bottom;
  • By default, inline elements will be arranged column by column in a row. When a row cannot be placed, it will automatically switch to the next row and continue to be arranged according to the column;

How to break away from document flow?

De streaming document flow means that after a node de streams the normal document flow, other nodes in the normal document flow will ignore the node and fill its original space. Once a document is out of stream, its height will not be included in the calculation of its parent node height, and the out of stream node does not occupy space. There are two ways to get elements out of the document flow: floating and positioning.

  • Using float will separate the element from the document flow and move it to the left / right boundary of the container or next to another floating element. The space occupied by the floating element will be filled by other elements. In addition, the area occupied after floating will not overlap with other elements;
  • Use absolute positioning(position: absolute;)Or fixed positioning(position: fixed;)It will also make the element out of the document flow, and the empty position will be automatically filled by subsequent nodes.

Box model

In CSS, any element can be regarded as a box, and a box is composed of four parts: content, padding, border and margin.

There are two kinds of box models: standard box model and IE box model. This is the standard formulated by W3C and IExplore.

If you set the following style for an element:

.box {
    width: 200px;
    height: 200px;
    padding: 10px;
    border: 1px solid #eee;
    margin: 10px;
}
Copy code

The standard box model holds that the actual size of the box = content (set width / height) + inner margin + border

therefore.boxThe width of the element content is200pxAnd the actual width iswidth + padding-left + padding-right + border-left-width + border-right-width = 200 + 10 + 10 + 1 + 1 = 222。

Ie box model holds that: the actual size of the box = the set width / height = content + inner margin + border

.boxThe actual width occupied by the element is200pxThe true width of the content iswidthpadding-leftpadding-rightborder-left-widthborder-right-width = 200 – 10 – 10 – 1 – 1 = 178。

At present, high-level browsers basically use the standard box model by default, while old directors such as IE6 use the IE box model by default.

A new attribute has been added in CSS3box-sizing, developers are allowed to specify what standard the box uses. It has two values:

  • content-box: standard box model;
  • border-box: ie box model;

Visual formatting model

Visual formatting model is a calculation rule used to process and display documents on visual media. Everything in CSS is boxes, and the visual formatting model is simply understood to specify how these boxes should be placed in the page. This model will depend on many factors in calculation, such as box size, box type, positioning scheme (floating or positioning), sibling elements or sub elements and some other factors.

It can be seen from the above figure that the visual formatting model involves a lot of content. Those interested in in in-depth research can see this W3C document in combination with the above figureVisual formatting model。 So here is a brief introduction to the box type.

The box type is determined by display. After setting display for an element, two display types of the box will be determined:

  • Outer display type: determines how the element itself is laid out, that is, what formatting context it participates in;
  • Inner display type: in fact, it is equivalent to treating the element as a container, specifying how its internal child elements are laid out and what formatting context they participate in;

outer display type

In terms of external display, box types can be divided into two categories: block level box and inline level box.

According to the above figure, the block level and intra row level boxes can be listed:

  • Block level box: display is block, list item, table, flex, grid, flow root, etc;
  • In line box: display is inline, inline block, inline table, etc;

All block level boxes will participate in BFC and are arranged vertically; All intra bank boxes will participate in IFC and are arranged horizontally.

Besides, what are the more specific differences between block, inline and inline block?

block

  • If it occupies a full line, it inherits the width of the parent element by default; Multiple block elements will be arranged from top to bottom;
  • Setting width / height will take effect;
  • Setting padding and margin will take effect;

inline

  • It will not occupy a full line, and the width changes with the content; Multiple inline elements will be arranged and displayed in a row from left to right. If a row cannot be displayed, it will wrap automatically;
  • Setting width / height will not take effect;
  • Setting padding and margin in the vertical direction will not take effect;

inline-block

  • It is a block element within a row, which does not occupy a row alone. It can be regarded as a block element that can be arranged left and right in a row;
  • Setting width / height will take effect;
  • Setting padding and margin will take effect;

inner display type

For the internal aspect, the element is actually regarded as a container, which is wrapped with text or other child elements. The type of container box is divided into four types according to the value of display:

  • Block container: establish BFC or IFC;
  • Flex container: establish FFC;
  • Grid container: establish GFC;
  • Ruby container: not much contact, no introduction.

It is worth mentioning that if the replaced element of img is declared as a block, it will not produce a container box, because the original intention of the replacement element, such as img, is to replace the content with a picture through SRC, without considering it as a container.

reference resources:

formatting context

The formatting context is CSS2 1. A concept in the specification, which roughly refers to a rendering area in the page, specifies how the sub elements in the rendering area are arranged and interact.

Different types of boxes have different formatting contexts. There are about four types:

  • BFC (block formatting context) block level formatting context;
  • IFC (inline formatting context) inline formatting context;
  • FFC (Flex formatting context) elastic formatting context;
  • GFC (grid formatting context) grid formatting context;

BFC and IFC play a very important role in CSS, because they directly affect the web page layout, so we need to deeply understand its principle.

BFC

Block formatting context, which is an independent rendering area, only block level boxes participate. It specifies how the internal block level boxes are laid out, and has nothing to do with the outside of this area.

BFC rendering rules

  • The inner boxes will be placed vertically, one by one;
  • The vertical distance of the box is determined by the margin, and the margins of two adjacent boxes belonging to the same BFC will overlap;
  • The left side of the margin of each element is in contact with the left side of the containing block border (for formatting from left to right, otherwise it is the opposite), even if there is floating;
  • The area of BFC will not overlap with the float box;
  • BFC is an isolated independent container on the page. The child elements in the container will not affect the external elements. And vice versa.
  • When calculating the height of BFC, floating elements also participate in the calculation.

How to create a BFC?

  • Root element: HTML
  • Non overflow visible element: overflow is not visible
  • Set float: float property is not none
  • Set positioning: position is absolute or fixed
  • Non block level elements defined as block level: display: inline block / table cell / table caption / Flex / inline Flex / grid / inline grid

BFC application scenario

1. Adaptive two column layout

Application principle: the area of BFC will not overlap with the floating area, so you can fix the width of the sidebar and float to the left, and trigger BFC for the content on the right, so that its width can adapt to the remaining width of the line.

<div>
    <div>aside</div>
    <div>main</div>
</div>
Copy code
.aside {
    float: left;
    width: 100px;
}
.main {
    <!--  Trigger BFC -- >
    overflow: auto;
}
Copy code

2. Clear internal float

The problem caused by floating is that the height of the parent element collapses, so the problem to be solved in clearing floating is to restore the height of the parent element to normal. The principle of using BFC to clear floating is that when calculating the height of BFC, floating elements also participate in the calculation. Just trigger the BFC of the parent element.

.parent {
    overflow: hidden;
}
Copy code

3. Prevent vertical margin merging

One of the principles of BFC rendering: the vertical margin under the same BFC will be merged. Therefore, if two elements are not in the same BFC, vertical margin merging can be prevented. How to make two adjacent sibling elements not in the same BFC? One of the elements can be wrapped with a layer, and then the BFC of its wrapping layer can be triggered, so that the two elements will not be in the same BFC.

<div>
    <div>a</div>
    <div>
        <div>b</div>
    </div>
</div>
Copy code
.demo3 .a,
.demo3 .b {
    border: 1px solid #999;
    margin: 10px;
}
.contain-b {
    overflow: hidden;
}
Copy code

For the above three examples, this can be combinedBFC application exampleIt’s better to watch together.

reference resources:CSS principle – formatting context

IFC

The formation conditions of IFC are very simple. Block level elements only contain inline level elements. It should be noted that when a block level element is inserted in IFC, two anonymous blocks will be generated to separate the parent element and generate two IFC.

IFC rendering rules

  • The sub elements are arranged one by one in the horizontal direction and downward from the top of the container in the vertical direction;
  • Nodes cannot declare width and height, where margin and padding are valid in the horizontal direction and invalid in the vertical direction;
  • Nodes are aligned in different forms in the vertical direction;
  • A rectangular area that can completely contain all the boxes on a line is called the line box of the line. The width of the wire box is determined by the containing box and the floating with it;
  • The left and right sides of the line box in IFC are generally close to its containing blocks, but the float elements will be arranged preferentially.
  • The line box height in IFC is determined by the line height calculation rule, and the heights of multiple line boxes under the same IFC may be different;
  • When the total width of inline boxes is less than the line box containing them, the horizontal rendering rule is determined by the text align attribute value;
  • When an inline box exceeds the width of the parent element, it will be divided into multiple boxes, which are distributed in multiple line boxes. If the child element is not set with forced line feed, the inline box will not be split and will overflow the parent element.

For the above IFC rendering rules, can you analyze the IFC environment of the following code?

<p>It can get <strong>very complicated</storng> once you start looking into it.</p>
Copy code

Corresponding to the above HTML string, the analysis is as follows:

  • P tag is a block container, and an IFC will be generated internally;
  • Because one line cannot be displayed completely, two line boxes are generated; The width of the junction box inherits the width of p; The height is determined by the line height of the inline box inside;
  • It can get: anonymous inline box;
  • Very complicated: stronginline box generated by tag;
  • Once you start: anonymous inline box;
  • looking into it.: Anonymous inline box.

reference resources:Inline formatting contexts

IFC application scenario

  • Horizontal centering: when a block is to be horizontally centered in the environment, setting it as inline block will generate IFC in the outer layer, and text align can make it horizontally centered.
  • Vertical center: create an IFC, use one of the elements to open the height of the parent element, and then set its vertical align: middle. Other in-line elements can be vertically centered under this parent element.

Steal a lazy, I won’t do the demo and picture.

stacking context

The page displayed on the computer display screen is actually a three-dimensional space. The horizontal direction is the X axis, the vertical direction is the Y axis, and the direction from the screen to the eyes can be regarded as the Z axis. HTML elements are arranged in a certain order on the z-axis according to the priority of their defined attributes, which is actually what the cascading context needs to describe.

Our first impression of cascading context may come from Z-index. We think that the larger its value is, the closer it is to the screen observer, the higher the cascading level is. Indeed, this is the case, but the content of cascading context is far from just that:

  • Z-index can the stacking order of elements in the stacking context, and its function is to cooperate with positioning;
  • In addition to Z-index, the display order of an element on the z-axis is also affected by the stacking level and stacking order;

Before looking at the stacking level and stacking order, let’s first look at how to generate a stacking context. A specific HTML element or CSS attribute generates a stacking context. MDN gives such a list. Elements that meet any of the following conditions will generate a stacking context:

  • HTML document root element
  • Declare the element with position: absolute / relative and Z-index value not auto;
  • Declare the element of position: fixed / sticky;
  • The child element of the flex container, and the Z-index value is not auto;
  • The child element of grid container, and the Z-index value is not auto;
  • Elements with opacity attribute value less than 1;
  • Elements whose mix blend mode attribute value is not normal;
  • Any of the following elements whose attribute value is not none:
    • transform
    • filter
    • perspective
    • clip-path
    • mask / mask-image / mask-border
  • Element with isolation attribute value of isolate;
  • -Element with WebKit overflow scrolling attribute value of touch;
  • The will change value sets any attribute, which will create elements of cascading context when the non initial value;
  • The value of the contain attribute is layout, paint or an element containing a composite value of one of them (such as contain: strict, contain: content).

Stacking level

The cascade level refers to the up-down order of nodes on the z-axis of 3D space. It can be divided into two cases:

  • In the same cascading context, it describes and defines the upper and lower order of the cascading context elements in the cascading context on the Z axis;
  • Among other common elements, it describes and defines the up and down order of these common elements on the Z axis;

The stacking level of ordinary nodes is determined by the stacking context in which they are located. The comparison of stacking levels is meaningful only in the current stacking context, and the comparison without the current stacking context becomes meaningless.

Stacking sequence

If there are multiple elements in the same cascading context, what is the cascading order between them?

The lower the following list is stacked, the higher the priority is. The visual effect is that it is easier for users to see (it will not be overwritten by other elements):

  • Border and background of cascading context
  • Child nodes with Z-index < 0
  • Block level non located child nodes in standard flow
  • Floating non positioned child nodes
  • Non positioned child nodes in the standard flow
  • Z-index: child node of auto / 0
  • Child nodes with Z-index > 0

How to compare the stacking levels of two elements?

  • In the same cascading context, comparing two elements is to compare according to the cascading order described in the above figure.
  • If you are not in the same cascading context, you need to compare the level of the cascading context of the two elements.
  • If two elements are in the same cascading context and the cascading order is the same, the later the definition in HTML, the higher the cascading level.

reference resources:Thoroughly understand CSS stacking context, stacking level, stacking order and Z-index

Values and units

CSS declaration consists of attributes and values, and there are many types of values:

  • Value: length value, used to specify the value of attributes such as element width, border width, font size, etc;
  • Percentage: can be used to specify the size or length, for example, depending on the width, height or default font size of the parent container;
  • Color: used to specify background color, color, etc;
  • Coordinate position: use the upper left corner of the screen as the coordinate origin to locate the position of elements, such as common background position, top, right, bottom, left and other attributes;
  • Function: used to specify the gradient of resource path or background image, such as URL (), linear gradient (), etc;

Some other values need units, such as width: 100px, where PX is the unit of length. In addition to PX, the commonly used length units include em, REM, VW / VH, etc. What’s the difference between them? When should they be used?

px

Screen resolution refers to the number of pixels in the horizontal and vertical direction of the screen, such as resolution 1920 × 1080 means 1920 pixels in the horizontal direction and 1080 pixels in the vertical direction.

PX represents the pixels in CSS. In CSS, it is the absolute length unit and the most basic unit. Other length units will be automatically converted into PX by the browser. But for the device, it is actually a relative length unit. For example, the width and height are 2px. Under the normal screen, it is actually 4 pixels, while under the retina screen with device pixel ratio of 2, it has 16 pixels. Therefore, when the screen size is consistent, the higher the screen resolution, the more delicate the display effect.

Here, there are some related concepts that need to be clarified:

Device pixels

The physical pixel of the device screen, which indicates the number of pixels in the horizontal and vertical direction of the screen; It means about the same as the screen resolution.

Device pixel ratio (DPR)

The device pixel ratio indicates that one CSS pixel is equal to several physical pixels.

Calculation formula: DPR = physical pixels / logical pixels;

In the browser, you can use window Devicepixelratio to get the DPR of the current screen.

Pixel density (DPI / PPI)

Pixel density is also called display density or screen density, abbreviated as DPI (dots per inch) or PPI (pixel per inch). From a technical point of view, PPI only exists in the field of computer display, while DPI only appears in the field of printing or printing.

Calculation formula: pixel density = pixel size of screen diagonal / physical size

For example, for the iPhone 6 with a resolution of 750 * 1334, its pixel density is:

Math.sqrt(750 * 750 + 1334 * 1334) / 4.7 = 326ppi
Copy code

Device independent pixels (DIP)

Dip is derived especially for Android devices. The reason is that Android screens have a wide range of sizes. Therefore, this concept is proposed in order to make the display as independent of the device as possible. It is calculated based on the screen density. When the screen density is 160, PX = dip.

Calculation formula: dip = PX * 160 / DPI

em

EM is one of the relative length units in CSS. It’s actually relative. Who is it? It has two meanings:

  • Used in font size is relative toParent elementFont size of, such as the parent element font size: 16px. When the child element is assigned font size: 2em, its font size will be 32px after calculation;
  • In other attributes, the font size relative to itself is used, such as width / height / padding / margin;

We all know that each browser will set a default font size for the HTML root element HTML, and this value is usually 16px. This is why 1em = 16px.

EM will be calculated layer by layer during calculation, for example:

<div>
    <p></p>
</div>
Copy code
div { font-size: 2em; }
p { font-size: 2em; }
Copy code

For the HTML with the above structure, since the font size of the root element html is 16px, the final calculated font size of the P tag will be 16 * 2 * 2 = 64px

rem

REM (root EM), like em, is also a relative length unit, but REM is relative to the root element of HTML.

Because rem is calculated based on the font size of HTML, it is usually used in adaptive websites or H5.

For example, when doing H5, the front end usually allows the UI to give 750px wide design drawings, and when developing, the page can be written based on the size of iPhone x 375px * 812px. In this way, the following JS can be used to automatically calculate the benchmark font size of the root element HTML according to the viewport width of the current page.

(function (doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        Psdwidth = 750, // width of design drawing
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if ( !clientWidth ) return;
            if ( clientWidth >= 640 ) {
                docEl.style.fontSize = 200 * ( 640 / psdWidth ) + 'px';
            } else {
                docEl.style.fontSize = 200 * ( clientWidth / psdWidth ) + 'px';
            }
        };

    if ( !doc.addEventListener ) return;
    //When binding events, it is best to cooperate with the anti shake function
    win.addEventListener( resizeEvt, debounce(recalc, 1000), false );
    doc.addEventListener( 'DOMContentLoaded', recalc, false );

    function debounce(func, wait) {
        var timeout;
        return function () {
            var context = this;
            var args = arguments;
            clearTimeout(timeout)
            timeout = setTimeout(function(){
                func.apply(context, args)
            }, wait);
        }
    }
})(document, window);
Copy code

For example, when the viewport is 375px, the calculated font size of HTML will be 100px. What are the benefits? The advantage is that it is convenient to write styles. For example, the height of the header measured from the design drawing is 50px, so we can write directly when writing styles:

header {
    height: 0.5rem;
}
Copy code

Each dimension measured from the design drawing can be divided by 100 to get the REM value of the current element without calculation, which is very convenient. Secretly tell you that if you replace 200 in the above JS code for calculating the font size of HTML tag with 2, you don’t need to divide by 100 when calculating rem. you can write as many REM as you can measure PX from the design drawing.

vw/vh

VW and VH are length units relative to the width and height of the screen viewport, respectively:

  • 1vw = the length of the viewport width divided into 1 part of 100;
  • 1vh = the height of the viewport is divided into 1 of 100 parts;

In JS, 100vw = window innerWidth,100vh = window. innerHeight。

The emergence of VW / VH makes it possible to write an adaptive layout scheme, and developers are no longer limited to rem.

In addition to VW / VH, there are Vmin and Vmax units relative to the viewport:

  • Vmin: take the one with the smaller median value of VW and VH;
  • Vmax: take the one with the larger median value of VW and VH;

Color system

There are many kinds of values used to represent colors in CSS, which is enough to form a system, so here is a special section to explain it.

according toCSS color draftThe color value types mentioned in can be roughly divided into these categories:

  • Color keyword
  • Transparent keyword
  • Currentcolor keyword
  • RGB color
  • HSL color

Color keyword

Color keywords are case insensitive identifiers that represent a specific color, such as white, black, etc;

The list of acceptable keywords has changed in the evolution of CSS:

  • CSS standard 1 only accepts 16 basic colors, called VGA colors, which are called VGA colors because they come from the color set displayed by VGA graphics card.
  • CSS standard 2 adds orange keyword.
  • From the beginning, browsers accepted other colors. Since some early browsers were X11 applications, most of these colors were X11 named color lists, although they were a little different. Svg 1.0 is the first standard to formally define these keywords; CSS color standard 3 also formally defines these keywords. They are often referred to as extended color keywords, X11 colors or SVG colors.
  • CSS color standard 4 can add the rebeccapurple keyword to commemorate web pioneer Eric Meyer.

The following picture shows 16 basic colors, also known as VGA colors. So far, there are 146 CSS color keywords, which can be viewed hereComplete color keyword list

It should be noted that if the color keyword is wrong when declared, the browser will ignore it.

Transparent keyword

Transparent keyword represents a completely transparent color, that is, the color will appear to be the background color. Technically speaking, it is black with alpha channel as the minimum value, which is the abbreviation of RGBA (0,0,0,0).

What are the application scenarios for transparent keywords?

Realize triangle

The following figure is a square filled with 4 borders. After understanding it, you probably know how to write triangles in CSS.

div {
    border-top-color: #ffc107;
    border-right-color: #00bcd4;
    border-bottom-color: #e26b6b;
    border-left-color: #cc7cda;
    border-width: 50px;
    border-style: solid;
}
Copy code

Principle of realizing triangle with transparent:

  • First, the width and height must be 0px, and the content is filled through the thickness of the border;
  • That edge needs to be colored, while the unwanted edge uses transparent;
  • What kind of posture triangle you want is completely determined by the positions of the colored and transparent sides of the top, bottom, left and right sides;
  • Isosceles triangle: set one side with color, and then the two adjacent sides are transparent, and the width is half of the color side; Right triangle: set one side to have color, and then any side next to it can be transparent.

See the following example:

Increase click area

The area of the button that is often clicked on the mobile terminal is very small, but because the actual effect is not good, it is not easy to make it larger, so a common method is to increase the click area of the button through a transparent border:

.btn {
    border: 5px solid transparent;
}
Copy code

Currentcolor keyword

Currentcolor will take the text color value of the parent element inherited by the current element or the declared text color value, that is, the color value after calculated.

For example, for the following CSS, the border color of the element will be red:

.btn {
    color: red;
    border: 1px solid currentColor;
}
Copy code

RGB [a] color

RGB [a] color is a color space composed of R (red) – G (green) – B (blue) – A (alpha).

In CSS, it has two representations:

  • Hexadecimal symbol;
  • Function character;

Hexadecimal symbol

The value range of each color in RGB is 00 ~ FF. The larger the value, the darker the color. Therefore, a color is normally composed of six hexadecimal characters plus # characters. For example, red is #ff0000.

If you need to add opacity to RGB color, you need to add the value of alpha channel, and its range is also 00 ~ FF. For example, a red with opacity of 67% can be written like this #ff0000aa.

When using hexadecimal symbols to represent a color, two hexadecimals are used to represent a color. If the two characters are the same, it can be reduced to write only one, for example, red #f00; Red with 67% opacity #f00a.

Function symbol

When RGB is expressed as a function, the range of each value is 0 ~ 255 or 0% ~ 100%, so red is RGB (255, 0, 0), or RGB (100%, 0, 0).

If you need to use a function to represent the color value with opacity, the range of values is 0 ~ 1 and the decimals between them or 0% ~ 100%. For example, red with 67% opacity is RGBA (255, 0, 0, 0.67) or RGBA (100%, 0%, 0%, 67%)

It should be noted that the three color values of RGB need to be written in the same way, either in numbers or in percentage, while the value of opacity can not be written in the same way as RGB. For example, RGB (100%, 0, 0) is invalid; RGB (100%, 0%, 0%, 0.67) is effective.

In the 4th generation CSS color standard, a new function writing method is added, that is, the comma separating the value in RGB can be changed into a space, and the comma in RGB and alpha can be changed into /. For example, the red with 67% opacity can be written as RGBA (255 0 / 0.67). In addition, the writing method of RGBA is incorporated into the RGB function, that is, RGB can directly write colors with opacity.

HSL [a] color

HSL [a] color is a color system composed of hue, saturation, brightness and opacity.

  • Hue (H) is the basic attribute of color, and the value range is 0360 or 0DEG360DEG, 0 (or 360) is red, 120 is green and 240 is blue;
  • Saturation (s) refers to the purity of color. The higher the color is, the purer the color is, and the lower it is, it will gradually turn gray, taking the value of 0 ~ 100%; 0% is gray, 100% full color;
  • Brightness (L), take 0 ~ 100%, 0% is dark and 100% is white;
  • Opacity (a), take 0Or 100%, orDecimals between 1 and;

In terms of writing method, you can refer to the writing method of RGB, but the values of parameters are different.

Set the opacity of a button to 67% of the red color, and all the following writing methods have the same effect:

button {
    color: #ff0000aa;
    color: #f00a;
    color: rgba(255, 0, 0, 0.67);
    color: rgb(100% 0% 0% / 67%);
    color: hsla(0, 100%, 50%, 67%);
    color: hsl(0deg 100% 50% / 67%);
}
Copy code

Tip: in chrome devtools, you can press and hold Shift + left mouse button to switch the color representation.

Media query

Media query refers to customizing different devices, specific device features or parameters to modify the style of the website.

You can give<link>Add the media attribute to specify which devices the style file can only take effect on. If it is not specified, it defaults to all, that is, it takes effect on all devices:

<link rel="stylesheet" src="styles.css" media="screen" />
<link rel="stylesheet" src="styles.css" media="print" />
Copy code

Which device types are supported?

  • All: applicable to all equipment;
  • Print: applicable to pagination materials and documents viewed on the screen in print preview mode;
  • Screen: mainly used for screen;
  • Speech: mainly used for speech synthesizer.

It should be noted that although the resource specified through media does not match its device type, the browser will still load it.

Except through<link>In addition to making the specified equipment effective, you can also use@mediaLet CSS rules take effect under specific conditions. The responsive page uses @ media to enable a page to adapt to PC, pad and mobile terminal at the same time.

@media (min-width: 1000px) {}
Copy code

Media query supports logical operators:

  • And: takes effect only when all query criteria are met;
  • Not: negative query criteria;
  • Only: the whole query will take effect only when it is matched. The common words are compatible with the old browser, and the media type must be specified when using;
  • Comma or or: match if one of the query criteria is met;

Media query also supportsNumerous media features, which enables it to write complex query conditions:

/*The minimum height of user equipment is 680px or screen equipment in vertical mode*/
@media (min-height: 680px), screen and (orientation: portrait) {}
Copy code

Common requirements

Custom properties

Before, we usually used variables in the preprocessor, but now CSS also supports the use of variables. You can reference it where you want to use it through custom attributes.

Custom attributes are also cascading like ordinary attributes. When declared under root, they are available within the scope of full-text files. If a custom attribute is declared under an element, it can only be used under it and its child elements.

Custom attributes must pass--xFormat declaration of, such as: – theme color: red; When using custom attributes, you need to use the VaR function. For example:

<!--  Define custom attributes -- >
:root {
    --theme-color: red;
}

<!--  Use variable -- >
h1 {
    color: var(--theme-color);
}
Copy code

The above figure shows the box shadow of dynamically adjusting elements using CSS custom attributes and JS. See this for detailscodepen demo

1px border solution

Retina display has a higher resolution than ordinary screens, so the 1px frame on the mobile end will look thick. In order to be beautiful, it is usually necessary to refine the line. Here is an article listing 7 schemes for reference:7 methods to solve the problem of retina screen 1px frame of mobile terminal

The last relatively perfect solution realized by pseudo class and transform is attached here:

Set only the bottom border of a single bar:

.scale-1px-bottom {
    position: relative;
    border:none;
}
.scale-1px-bottom::after {
    content: '';
    position: absolute;
    left: 0;
    bottom: 0;
    background: #000;
    width: 100%;
    height: 1px;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
}
Copy code

Set 4 borders at the same time:

.scale-1px {
    position: relative;
    margin-bottom: 20px;
    border:none;
}
.scale-1px::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    border: 1px solid #000;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 200%;
    height: 200%;
    -webkit-transform: scale(0.5);
    transform: scale(0.5);
    -webkit-transform-origin: left top;
    transform-origin: left top;
}
Copy code

Clear float

What is floating: floating elements leave the document flow and float left / right until they encounter a parent element or another floating element.

Why should we be clear about floating and what problems does it cause?

Because the floating element will deviate from the normal document flow and will not occupy the position of the document flow, if there are floating elements under a parent element, the parent element cannot be supported by the floating element. In this way, the parent element will lose its height, which is the so-called height collapse of the parent element caused by floating.

Once the height of the parent element collapses, it will affect the layout of the following elements. In order to solve this problem, you need to clear the float and restore the height of the parent element. What should you do?

Here are two methods: BFC and clear.

BFC clear float

As mentioned earlier when introducing BFC, when calculating the height of BFC, the height of floating sub elements will also be included. Using this rule, you can clearly float.

Suppose that there are only two child elements inside a parent element, and they all float to the left. At this time, if the parent does not set the height, the height of the parent will be 0 because the height collapse is caused by the floating. At this time, as long as a BFC is created for the parent, its height can be restored.

There are many ways to generate BFC. We can set overflow: Auto to the parent element to simply clear the floating of BFC. However, in order to be compatible with ie, it is best to use overflow: hidden.

.parent {
    overflow: hidden;
}
Copy code

Clearing the float through overflow: hidden is not perfect. When the element has a shadow or a drop-down menu, it will be truncated, so the use of this method is relatively limited.

Clear floating through clear

I’ll post the conclusion first:

.clearfix {
    zoom: 1;
}
.clearfix::after {
    content: "";
    display: block;
    clear: both;
}
Copy code

The core principle of this writing method is to generate a block level element with empty content after the last child element of the parent element through the:: after pseudo element, and then move this pseudo element to the back of all floating elements before it through clear, and draw a diagram to understand it.

You can combine thiscodepen demoUnderstand the clear floating principle in the figure above together.

In the above demo or figure, in order to show the need, the content of the pseudo element is set to:: after. In actual use, it needs to be set to an empty string with its height of 0, so that the height of the parent element is supported by the actual child element.

This method is basically a scheme used by everyone to clear floating, which is very general.

reference resources:CSS floating and clear floating, sort it out

Eliminate browser default styles

For the same type of HTML tags, different browsers often have different performances. Therefore, when making websites, developers usually need to clear the default styles of these browsers to make the web pages consistent on different browsers.

Eric A. Meyer, a CSS master, has done this for a long time. It is to write a bunch of general styles to reset the browser’s default styles. These styles are usually placed in a named reset CSS file. Like the master’sreset.cssIt says:

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}
Copy code

His job is reset CSS is said to be the most widely used scheme for styling.

Except reset In addition to CSS, it appeared again laterNormalize.css。 About normalize CSS, its author necolas wrote an article to introduce it and talked about it and reset The difference between CSS. This is a translation of the article he wrote:Let’s talk about normalize css

The article introduces to: normalize CSS is just a small CSS file, but it provides a high degree of consistency across browsers in the default HTML element style. Compared with traditional CSS Reset, normalize CSS is a modern, high-quality alternative for HTML5, and it is now used by many well-known frameworks and websites.

Normalize. The specific style of CSS can be seen hereNormalize.css

Different from reset css,Normalize. CSS has the following characteristics:

  • reset. CSS sets the default style for almost all labels, while normalize CSS selectively protects some valuable default values;
  • Fixed many browser bugs, and this is reset CSS didn’t do it;
  • It won’t make your debugging tools messy. On the contrary, reset CSS sets many default values, so you often see a lot of inheritance styles in browser debugging tools, which is very messy;
  • Normalize. CSS is modular, so you can selectively remove parts that will never be used, such as the generalization of forms;
  • Normalize. CSS has detailed documentation;

Long text processing

Default: the character is too long and overflows the container

Line feed for excess characters

Use hyphen when character exceeds position

Single line text exceeds ellipsis

Multiline text exceeds ellipsis

See examples of these scenarios above:codepen demo

Interestingly, just two days ago, I saw that chokcoco also wrote an article on text overflow, mainly focusing on the treatment of text overflow of the whole block. What is a whole piece of text? For example, the following technical tags belong to the whole text:

In addition, he has made compatibility processing for IOS / safari. Those who are interested can read:Research on CSS whole block text overflow and ellipsis

Horizontal vertical center

Let the element appear in the form of horizontal and vertical center in the parent element, which is nothing more than two cases:

  • Single line text, inline or inline block elements;
  • Block level box with fixed width and height;
  • Block level box without fixed width and height;

With all the horizontal and vertical centering schemes from the following to, write one herecodepen demoIt is better to read with examples.

Single line text, inline, or inline block elements

horizontally

If such elements need to be horizontally centered, the parent element must be a block element(block level), and the style needs to be set on the parent element as follows:

.parent {
    text-align: center;
}
Copy code

Vertical center

Method 1: achieve the effect of vertical centering by setting the upper, lower and inner spacing to be consistent:

.single-line {
    padding-top: 10px;
    padding-bottom: 10px;
}
Copy code

Method 2: through settingheightandline-heightConsistent vertical center:

.single-line {
    height: 100px;
    line-height: 100px;
}
Copy code

Block level box with fixed width and height

Method 1: absolute + negative margin

Method 2: absolute + margin Auto

Method 3: absolute + calc

Block level box without fixed width and height

Here are six methods for referenceYan HaijingThe two line height and writing mode schemes in the article I wrote made me exclaim: is there such an operation? Learned, learned.

Method 1: absolute + transform

Method 2: line height + vertical align

Method 3: writing mode

Method 4: table cell

Method 5: Flex

Method 6: Grid

Common layout

Two column layout (sidebar fixed width, main column adaptive)

Several examples are written for these schemes:codepen demo

Method 1: float + overflow (BFC principle)

Method 2: float + margin

Method 3: Flex

Method 4: Grid

Three column layout (fixed width on both sides and adaptive main column)

Several examples are written for these schemes:codepen demo

Method 1: Holy Grail layout

Method 2: double wing layout

Method 3: float + overflow (BFC principle)

Method 4: Flex

Method 5: Grid

Multi column contour layout

Better read with examples:codepen demo

Method 1: padding + negative margin

Method 2: set the parent background picture

Three row layout (head and tail fixed height, main column adaptive)

Four methods are listed, which are based on the following HTML and CSS, and the reading effect is better when combined with examples:codepen demo

<div>
    <header></header>
    <main>
        <div></div>
    </main>
    <footer></footer>
</div>
Copy code
html,
body,
.layout {
    height: 100%;
}
body {
    margin: 0;
}
header, 
footer {
    height: 50px;
}
main {
    overflow-y: auto;
}
Copy code

Method 1: calc

Method 2: absolute

Method 3: Flex

Method 4: Grid

It ends

This is the article I completed after two weeks of continuous writing. It can be regarded as my own summary of CSS. Although it is very long, it is not enough to cover all the knowledge of CSS. For example, animation and some new features of CSS3 are not involved at all, because it is estimated to have tens of thousands of words to write down (in fact, it is lazy).

It’s not easy to draw codewords. If you like it or it’s of any help to you, I’ll give you a little help and praise it. At the same time, I hope I can stick to writing carefully, because I will feel very happy if I can help more front-end ers while summarizing and improving myself.
Learn more and join our front-end learning circle