New knowledge storeFront end from entry to groundFor attention, star and suggestions, update from time to time ~


You don’t see the total set: from scratch big front-end base building journey (simple, constantly updated ~) ten thousand word long catalogue, feel good, feel free to like it

preface

I attached links to articles worthy of expansion at the end of the questions, which will have detailed explanation and case analysis. If you want to talk about the technology with the interviewer, you can have an in-depth look at this article.

Finally, organizing is not easy, so.. If it makes you happy… What a waste of time… However, if you don’t like it, you can’t find it later 🤔🤔

What is the difference between the standard CSS box model and the lower version IE box model?

Content-box: width = content + border + padding + margin

Border-box: width = content + border-padding + margin

Difference: The height and width of the standard box model are the width of the content, while the width and height of the IE box model include the content+padding+border part.

How is the CSS priority algorithm calculated?

! Important > Inline Style > ID > Class > Tags > Wildcard > Inheritance > Default

weighting

The particularity is divided into four levels, and each level represents a class of selectors. The value of each level is the number of selectors it represents multiplied by the weight of this level. Finally, the value of all levels is added up to obtain the special value of the selectors.

The four levels are defined as follows:

Suppose the zero class:! Important weight 10000 first class: represents the inline style, such as: style= “”, weight 1000. Second class: represents an ID selector, such as #content, with a weight of 0100. Third class: represents classes, pseudo-classes, and attribute selectors, such as.content, with a weight of 0010. Fourth class: represents tag selectors and pseudo-element selectors, such as div P, with a weight of 0001. Fifth class: universal selector (*), child selector (>), adjacent sibling selector (+), weight 0000 Example as follows:

0,0,0,5 + 0,0,0,5 =0,0,0,10 } 100. 100 1 1. 10 1 ---> sum 0213Copy the code
  1. The weights are the same, so what goes on the back overwrites what goes on the front
  2. The weight is the same, one is written in the external stylelinkIntroduce another inside stylestyleIntroduce, introduce what’s later in the order overwrite what’s earlier
  3. The weight of the inline style is 1,0,0,0, and the weight of the 10 id selectors is also 0,10,0,0. The inline style has a higher priority

How do I center div?

Ps: select the following sample can be directly debugging in the console, pure manual build, the author is very sincere

Use the following styles:

Margin: 0 auto;

The target element is required to be of a fixed width and to have a margin to the left and right of the parent element.

This applies when there are multiple block-level elements in the parent element

<div class="container">
  this is inner text
  <div classs="ele2">
      this is another block element
  </div>
</div>
Copy the code
.container{
  width: 300px;
  border: 1px solid grey;
  text-align: center;
}
.ele2{
  border: 1px solid grey;
  width: 200px;
  margin:0 auto;
}
Copy the code
this is inner text

this is another block element

If margin is set to auto, the computed value is 0

2. Absolute + transform

The transform sets the percentage parameter relative to its own size

<div class="container">
   this is inner text
  <div class="ele1">
    this is a block element
  </div>
</div>
Copy the code
.container{
    height: 100px;
    width: 200px;
    position: relative;
    border: 1px solid grey;
  	text-align: center;
}
.ele1{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);  
    width: 100px; // This is optional. The default value is half the width of the parent elementborder: 1px solid # 888;
}
Copy the code
this is inner text

this is a block element

Ele1 may not be set to width, so the width of ele1 is calculated to be half the width of the parent element – the width of the left and right border

3、 absolute + margin

Margin sets the percentage parameter relative to the parent element, so this method requires the child element to be fixed width and set to half its own width.

Transform: translateX(-50%); margin-left: -50px;

.ele1{
    position: absolute;
    left: 50%;
    margin-left: -50px; // A negative value, set to half the width of the element itselfwidth: 100px; // It must be set hereborder: 1px solid # 888;
}
Copy the code
this is inner text

this is a block element

4、 flex

I don't have to say thatCopy the code

5、 absolute + margin: auto

Suitable for vertical centerCopy the code

More layout please click the “dry” CSS layout of edible | horizontal, vertical, multiple columns, coherent set of horizontal and vertical center have been listed, hand make sample, can debug on the page

What are the values of display? What is their role?

value role
none The element will not be displayed after use
block The element is displayed as a block-level element, preceded by a newline character
inline Display default value. After using the primary color to display inline elements, before and after no line breaks
list-item Use the back element to display as a list
run-in After use, elements are displayed as block-level elements or inline elements, depending on context
table When used, it is displayed as a block-level table (similar<table>), followed by a newline character
inline-table After use, the element is displayed as an inline table (similar<table>) without a newline character
table-row-group The element is displayed as a group of one or more rows (similar<tbody>)
table-header-group The element is represented as a group of one or more rows (similar<thead>)
table-footer-group Elements are displayed as one or more row groups (similar<tfoot>)
table-row The element is displayed as a table row (similar<tr>)
table-column-group The element is displayed as a grouping of one or more columns (similar<colgroup>)
table-column The element is displayed as a cell column (similar<col>)
table-cell The element is displayed as a table cell (similar< td > and < th >)
table-caption The element is displayed as a table title (similar<caption>)
inherit Specifies that the value of the display attribute should be integrated from the parent element

The origin and characteristics of different values of position?

Relative: generates relatively positioned elements. The origin of the position is the element itself, occupying a certain space in the original document flow position.

Absolute: An element that generates an absolute position, starting at the upper left corner of the parent element whose position is set to absolute or relative.

Fixed (old IE not supported) : Generates an absolutely positioned element that is removed from the normal document flow when positioned relative to the browser window, with no space reserved for the element.

Static: the default value. Without positioning, the element appears in the normal stream (top, bottom, left, right, z-index declarations are ignored).

Inherit: Inherits the value of the position property from the parent element.

Sticky: The element is positioned according to the normal document flow and can be considered a mixture of relative and fixed positioning. The element is described as relative when it is in the display area of the screen or scrolling element, and fixed when it is rolled out of the display. For details, see CSS Position attribute and its sticky attribute value

How to create a triangle with pure CSS

Ps: select the following sample can be directly debugging in the console, pure manual build, the author is very sincere

Set the width and height of block elements to 0, and set the color of only one edge and the color of the other three edges to transparent.

<div class="container">
  <div class="triangle-top"></div>
   <div class="triangle-left"></div>
   <div class="triangle-right"></div>
   <div class="triangle-bottom"></div>
</div>
Copy the code
.container{
  display: flex;
  justify-content: space-between;
  width: 400px;
}
.container div{
  width: 0;
  height: 0;
  border-width: 20px;
  border-style: solid;
  border-color: transparent;
}
.container .triangle-top {
    border-bottom-color: orange; 
}
.container .triangle-left {
    border-right-color: orange; 
}
.container .triangle-right {
    border-left-color: orange; 
}
.container .triangle-bottom {
    border-top-color: orange; 
}
Copy the code

Remember to center arrows with relative positioning

How does float work and when does it need to be cleared? How to clear the float?

What is floating

When the element is floated, it leaves the flow of the document, rises half a level, and moves in the specified direction until it hits the boundary of the parent element or another floating element stops

What is hierarchy

If the entire element is considered a layer, the lower half is the element itself (background style, etc.) and the upper half is the content within the element

For example,

<div class="container">
  <div class="box1">box1</div>
   <div class="box2">box2</div>
   <div class="box3">box3</div>
</div>
Copy the code
.container{
 width: 40px;
 border: 1px solid black;
}
.container div{
  width: 100%;
  height: 30px;
}
.box1 {
  background: yellow;
}
.box2 {
    background: orange; 
}
.box3 {
     background: pink; 
}
Copy the code

When all three boxes are not floating

box1
box2
box3

When you add float:left to box2, the arrangement of three boxes becomes

box1
box2
box3

As Box2 floats out of the document stream, Box3 moves up and is obscured by Box2. But the text box3 in the box3 box has not moved up!!

The little knowledge

  1. Floating elements float between each other and do not form a flow. Floating elements always align their top with the bottom of the element from the previous standard flow (unfloated elements).
  2. Position: Absolute and float implicitly change the display type, except display: None, whenever position is set: Absolute or float, both make the element display as display:inline-block, and you can set the length and width

Problems with floating:

1. Influence the position of sibling elements

2. Make the parent element collapse

How to clear float defects:

  • The parent box defines height;
  • Add an empty div tag to the last floating element, and add the style clear: both;
  • Parent tags that contain floating elements add style overflow to hidden/both;
  • The parent div defines zoom;

Clear float essence

  1. Use the CLEAR property of the CSS to add clear:both
  2. Triggers the BFC of the floating element’s parent so that the parent can contain the floating element

What is the CSS preprocessor/post-processor? Why use them?

What is a CSS preprocessor? CSS preprocessor defines a new language, its basic idea is to use a special programming language, add some programming features to CSS, CSS as a target file, and then developers just use this language for CSS coding.

Why use CSS preprocessors?

CSS is just a markup language. You can’t customize variables or reference them.

For example: less, sass, stylus, which is used to precompile SASS or LESS, increases the reuse of CSS code, as well as levels, mixins, variables, loops, functions, etc., which are very convenient for writing and developing UI components.

The CSS has the following disadvantages:

  • Syntax is not strong enough, such as the inability to write nested, resulting in many repetitive selectors to be written in modular development;
  • The absence of variables and a reasonable style reuse mechanism makes it difficult to maintain logically related attribute values that must be repeatedly printed as literals.

Precompilation can easily lead to abuse of descendant selectors

Advantages of using a preprocessor

  • Provides a style layer reuse mechanism missing from the CSS layer
  • Reduce redundant code
  • Improve the maintainability of style code

Details you can refer to: [Sass. Vs. Less | introduction and comparison 】

A post-processor is a preprocessor that processes and generates the CSS. It belongs to the CSS preprocessor in the broad sense. We’ve been using CSS post-processors for a long time, most notably CSS compression tools (such as clean-CSS), but we haven’t talked about them separately before. There is also Autoprefixer, which is popular recently and automatically handles compatibility issues based on browser support data on Can I Use.

Reasons for use:

  • The structure is clear and easy to expand
  • It’s easy to mask differences in browser private syntax
  • Multiple inheritance can be easily implemented

What’s the difference between a double colon and a single colon in ::before and :after?

Pseudo-classes in CSS are always represented by a single colon:, such as hover, :active, and so on

Pseudo-elements already exist in CSS1, when the syntax was denoted by:, such as :before and :after. Later, it was revised in CSS3. In order to distinguish pseudo-elements from pseudo-classes, pseudo-elements were denoted by ::, such as ::before and ::after.

Since older versions of Internet Explorer are not compatible with double colons, developers continue to use the old syntax :after to indicate pseudo-elements for compatibility with browsers.

If you want the inserted content to appear before its element content, use ::before, or if not, use ::after;

In code order ::after also generates later content than ::before.

If the stack view is pressed, ::after generates content above that generated by ::before

The difference between pseudo-elements and pseudo-classes

CSS introduced the concept of pseudo-classes and pseudo-elements to format information beyond the document tree.

  • Pseudo-classes are used to style existing elements when they are in a state that changes dynamically based on user behavior. For example, when a user hovers over a specified element, we can use :hover to describe the state of the element. Although it is similar to a normal CSS class in that it can style existing elements, it can only style elements in a state that the DOM tree cannot describe, so it is called a pseudo-class.

  • Pseudo-elements are used to create and style elements that are not in the document tree. For example, we can append some text to an element and style the text with :before. Although this text is visible to the user, it is not actually in the document tree.

CSS pseudo-classes

The selector The sample example
[:link] a:link Select all unvisited links
[:visited] a:visited Select all visited links
[:active] a:active Select active links
[:hover] a:hover The state of placing the mouse over the link
[:focus] input:focus The selection element has focus after input

CSS pseudo-elements

The selector The sample example
[:first-letter] p:first-letter Select each

First letter of the element

[:first-line] p:first-line Select each

The first row of the element

[:first-child] p:first-child The selector matches those belonging to the first child of any element

The element

[:before] p:before At the end of each

Element before inserting content

[:after] p:after At the end of each

Insert content after the element

[:lang(language)] p:lang(it) for

The lang attribute of the element selects a starting value

What is the difference between rGBA () and opacity?

  • opacityTransparency applied to elements and all content within elements, including text;
  • rgba()Applies only to the element’s own color or its background color. Child elements do not inherit the transparency effect.

What does the CSS property Content do?

The Content attribute applies exclusively to the before/after pseudo-element and is used to insert generated content. The most common use is to clean up floats using pseudo-classes.

Extension: How do I implement CSS counters through the CSS Content property?

CSS counters are implemented by setting counter-reset, counter-increment and counter()/counters() with after/before pseudo-classes.

What’s the difference between PX, EM and REM?

  • Px relative to the screen resolution of the monitor.

    Characteristics of PX

    • IE cannot adjust font sizes that use PX as a unit;
    • Most foreign websites can be adjusted because they use EM or REM as font units;
    • Firefox can adjust PX and EM, REM.
  • Em is a unit of relative length. Font size relative to the text in the current object. If the current font size for inline text has not been manually set, it is relative to the browser’s default font size.

    Characteristics of the EM

    • The em value is not fixed;
    • Em inherits the font size of the parent element.

Note: The default font height for any browser is 16px. All untuned browsers fit: 1em=16px.

  • Rem is a relative unit (root em) added to CSS3. This unit is different from EM in that when rem is used to set the font size for elements, it is still the relative size, but only relative to the root HTML element.

Rem is now supported by all browsers except IE8 and earlier.

A height adaptive div that has two divs, one 100px high, and wants the other to fill the remaining height.

  1. usecalc
.div1{
	height: 100px;
}
.div2 { 
	height: calc(100%-100px); 
}
Copy the code
  1. Absolute positioning
.container{
	position: relative;
}
.div1{
	height: 100px;
}
.div2 { 
	position: absolute;
	top: 100px;
  bottom: 0;
}
Copy the code
  1. flexlayout
.container { 
  display:flex; 
  flex-direction:column; 
} 
.div1{
	height: 100px;
}
.div2 { 
	flex:1; 
}
Copy the code

Transition, Transform and animation

Transform:

The transform property is a static property. Once written to the style property, it will be displayed without any change. The main purpose of transform is to do special deformation of elements. It defines the static style of elements to achieve deformation, rotation, scale, shift, perspective and other functions.

Transition

The Transition property is a simple animation property. It is a simplified version of animation. It is used for simple web effects.

For example, you have two styles:

.position{
    left:100px;
    top:100px;
}
.position1{
    -webkit-transition:left 0.5s ease-out;
    left:500px;
    top:500px;
}
Copy the code

The class of the element is position. When you add position1 to a classList or replace position with position1, an element’s attributes change, triggering webKit-transition, and animation is performed with the specified starting and ending values of the attributes. This is a simple two-point change process, which greatly simplifies the complexity of animation properties.

The transition from position1 animation is performed when your left attribute changes (only the left attribute changes, no other attributes are added to the animation).

Specify the response property as all in the transtion property, which responds to and animates all attributes of the element.

Animation:

This property is introduced in the official Introduction as an extension of the Transition property. But this simple introduction contains something not simple: Keyframes.

Look at a simple example of keyframes:

@keyframes 'wobble'{
  0%{
   left:100px
}
   30%{
   left:300px;
}
  100%{
   left:500px; }}.animate{
left:100px;
   -webkit-animation:wobble 0.5 s ease-out;
   -webkit-animation-fill-mode:backwards;
}
Copy the code

The code above shows a keyframes’ wobble ‘where 0% represents the value of the property at different time points in the change. You can accurately control the effect of the property at any time point in the animation change. The animation calculates the attributes of the element animation according to the way the attributes change provided by the keyframes.

It itself is used instead of some purely expressive javascript code to animate, and can explicitly control the current frame’s property values via the KeyFrame.

Animation-fill-mode: this property indicates whether the style specified by (from/0%) or the style specified by (to/100%) is the style after the animation is completed. This is very convenient for us to control the end of the animation style, to ensure the overall consistency of the animation.

What is line-height?

Line-height refers to the height of a line, including the spacing between the lines, which is actually the distance from the next line baseline to the previous line baseline.

If a tag does not define a height attribute (including percentage height), then the final height of the tag must be determined by line-height

To put it another way, if a text div is not set to height and its line height is set to 0, the div will not be split.

<div class="container">
  <div class="ele">
    this is inner text
  </div>
  <div class="ele1">
    this is inner text
  </div>
</div>
Copy the code
.container{
    width: 220px;
    height:100px;
    border: 1px solid grey;
}
div{
   margin-top: 20px;
   border: 1px solid grey;
}
.ele{
 line-height:0;
}
Copy the code
this is inner text
this is inner text

Details can be move to edible “dry” CSS layout, pure Html example, adjustable | horizontal, vertical, the line – height part in multiple columns

CSS margin overlap and prevention methods

The margins of two adjacent boxes (which may be siblings or ancestors) can be combined to form a single margin. This merging of margins is called folding, and the combined margins are called folded margins.

The folding results follow the following calculation principles:

When two adjacent outer margins are positive, the result of folding is the greater of them; When two adjacent margins are both negative, the result of folding is the greater value of their absolute values; When two margins are positive and negative, the result of folding is the sum of them;

When does margin overlap not occur?

  1. Horizontal margins never overlap.
  2. If one of the adjacent box models is floating, the vertical margins do not overlap, nor do the vertical margins between the floating box model and its children.
  3. The margin between the element with overflow set and its children is not overlapped (unless overflow is visible).
  4. With the box model set to position: Absolute, vertical margins do not overlap, nor do they overlap with their children.

In fact, margin overlap is mainly due to the overlap of two elements under the same BFC. The solution is to make the element generate a new BFC context with some attributes

What is BFC? How do I trigger the BFC? What’s the use?

Block formatting context (BFC). It is a separate rendering area, with only block-level box participation, which dictates how the internal block-level box is laid out and has nothing to do with the outside of the area.

BFC layout restriction rules

  • The internal boxes will be placed vertically, one on top of the other.

  • The vertical distance of the Box is determined by margin. Margins of two adjacent boxes belonging to the same BFC will overlap.

  • The left side of the margin box of each box (block box vs. row box) touches the left side of the border box containing the block (for left-to-right formatting, otherwise the opposite). This is true even if there is a float. That is, a BFC neutron element does not exceed its inclusion block.

  • The region of the BFC does not overlap with the float box.

  • A BFC is a separate container on a page, and the child elements inside the container do not affect the outside elements. And vice versa.

  • When calculating the height of the BFC, floating elements are also involved.

BFC trigger mode

  1. The root element, the HTML tag
  2. Float elements: Float values are left and right
  3. The overflow value is not visible, but auto, Scroll, and hidden
  4. The display value is inline-block, table-cell, table-caption, table, inline-table, flex, inline-flex, grid, inline-grid
  5. Positioning elements: Position values are Absolute and fixedNote: display: tableThe BFC can also be generated because the Table generates an anonymous table-cell by default. This anonymous table-cell generates the BFC.

Landing the role of

The BFC is a separate container on the page, and the child elements inside the container do not affect the outside elements and vice versa. We can do a lot with this feature of the BFC.

  1. Margins fold under the same BFC

  2. BFC can contain floating elements (clear floating

  3. The BFC prevents elements from being overwritten by floating elements

BFC example and detailed explanation

display: none; With the visibility: hidden; What’s the difference?

Both make elements invisible.

The difference between describe
The document flow display: none; Renders elements completely out of the render tree, taking up no space while rendering. visibility: hidden; Renderer elements continue to occupy space, but the content is not visible;
inheritance display: none; Due to the disappearance of elements from the rendering tree, the descendant node attribute cannot be displayed by modifying the descendant node attribute. visibility:hidden; The descendant node disappears because it inherits the hidden, by setting visibility: visible; Can make descendant nodes explicit;
Rendering effects Modifying the display attribute of an element to make it disappear or appear usually causes backflow. Modifying the visibility property will only cause a redraw
Read the screen editor Unable to readdisplay: noneElement content of; The visibility: hidden element will be read;

What are the ways to hide elements?

  • visibility: hidden: Hides an element, but the space occupied by the element still exists.
  • opacity: 0: Make an element completely transparent;
  • Position: Absolute + a large left negative position: Positions the element outside of the visible region;
  • display: none: the element is not visible and no longer takes up space in the document.
  • transform: scale(0): Sets the zoom of an element to infinitesimally small. The element will not be visible and its original position will be preserved.
  • <div hidden="hidden">: HTML5 attributes, effects and display: None; Same, but this property is used to record the state of an element;
  • height: 0: Sets element height to 0 and eliminates borders, sometimes synchronouslyoverflow: hidden;
  • filter: blur(0): CSS3 attribute, the greater the value in parentheses, the greater the degree of Gaussian blur of the image, and the image can disappear when it reaches a certain degree;

What is the cause of the invisible space between Li and Li? What’s the solution?

The default behavior of browsers is to render a white space character (whitespace newline TAB) between inline elements as a space. A newline produces a newline character, which becomes a space, which of course takes up the width of one character.

Solutions:

  1. Write all the < li> code in one row
  2. willulThe character size is set directly to 0, resetliCharacter size of
  3. willulSet the character interval to -5px, resetliCharacter size of
.wrap ul{letter-spacing: -5px; }.wrap ul li{letter-spacing: normal; }Copy the code
  1. Set up theliThe properties of theFloat: left;

Although I haven’t written ul in a while…

How does JS get the position and width of the box model

  1. Dom.style. width/height this method can only get the width and height of inline styles, and styles are usually not written inline, so this method is not suitable for most development nowadays;
  2. Window.getcomputedstyle (dom).width/height getComputedStyle() is a method that gets the final CSS attribute values of the current element; Compatibility is good.
  3. GetBoundingClientRect dom. GetBoundingClientRect () is used to retrieve an element relative to the position of the window. Top, right, bottom, left,height,width,x,y
const rectObject = dom.getBoundingClientRect()
Copy the code
  • Rectobject. top: The distance from the top of the element to the top of the window;
  • Rectobject. right: the distance from the right side of the element to the left side of the window;
  • Rectobject. bottom: Distance from the bottom of the element to the top of the window;
  • Rectobject. left: the distance between the left side of the element and the left side of the window;
  • Rectobject. width: element width;
  • Rectobject. height: element height;
  • Rectobject. x: horizontal distance between element content and viewport;
  • Rectobject. y: The vertical distance between the element’s content and the viewport;

How to make Chrome support text smaller than 12px

Transform: Scale () for chrome kernel, add webKit prefix, scale with transform:scale()!

.text {
    -webkit-transform: scale(0.8);
}
Copy the code

How does the browser determine if an element matches a CSS selector

The browser first generates a collection of elements, usually from the index of the last section (or all elements if there is no index). Then it matches up, and if it doesn’t match the previous part, it removes the element from the set until all the other selectors match, and the element that’s still in the set matches the selector.

For example, there are selectors: body.ready #wrapper >.lol233

For each element in the set, remove the element from the set if its parent ID is not #wrapper. If you can’t find an element whose tagName is body and whose class has a ready element, delete the element from the set.

At this point the selector match is complete, and all elements still in the collection are satisfied.

It matches from back to front because of efficiency and the parsing direction of the document flow. Efficiency needless to say, finding elemental fathers and previous brothers is faster and more convenient than traversing all sons.

The direction of document flow parsing is due to the fact that CSS now determines the match of an element as long as it determines all the elements that have appeared before the document flow. Even if the HTML has not been loaded, the browser can fully determine the attributes of the elements that have been loaded.

Why set is mainly efficiency. Based on the assumption that the number of CSS rules is much smaller than the number of elements and the use of indexes, it is much faster to traverse each CSS Rule through a set filter than to traverse each element and then traverse each Rule match.

How to implement 1px on mobile

The same 1px, 1px on the mobile will look thick.

In earlier mobile devices, screen pixel density was low, such as the iphone3, which had a resolution of 320×480. On the iphone3, one CSS pixel was indeed equal to one physical pixel on the screen. Later, with the development of technology, the pixel density of the screen of mobile devices became higher and higher. Starting from iphone4, Apple introduced the so-called Retina screen, with the resolution doubled to 640×960, but the screen size remained unchanged, which meant that the pixels on the same size screen were doubled. At this time, One CSS pixel is equal to two physical pixels.

Use JavaScript to check if the browser can handle a 0.5px border, and if so, add a class to the element.

Scheme 2: Use image realization to generate an image with transparent edges, and display border-image: URL (border-.gif) 2 repeat;

Scheme 3: Multi-background gradient implementation Set 1px gradient background, 50% color, 50% transparency, but can not achieve rounded corners

Solution 4: the pseudo-class + transform removes the border from the original element and then rewrites the border with :before or :after and reduces the scale of the transform by half. The original element is positioned relative to the new border element

Scheme 5(recommended) : Use Viewport + REM

var viewport = document.querySelector("meta[name=viewport]"); // Set viewPort if (window) according to the device pixel.devicePixelRatio= =1) {
  viewport.setAttribute('content', 'width=device-width.initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no');
}
if (window.devicePixelRatio= =2) {
  viewport.setAttribute('content', 'width=device-width.initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no');
}
if (window.devicePixelRatio= =3) {
  viewport.setAttribute('content', 'width=device-width.initial-scale=0.3333333333333333, maximum-scale=0.3333333333333333, minimum-scale=0.3333333333333333, user-scalable=no'); } // Set the rem reference value of the corresponding viewportvar docEl = document.documentElement;
var fontsize = 16* (docEl.clientWidth / 375) + 'px';
docEl.style.fontSize = fontsize;
Copy the code

I will not go into details here. Five plan implementation and detail please click [viewport and 1 px | tools: this is a 1 px, designer: no, it’s not 】

What properties of CSS can be inherited?

1. Font series properties

  • Font-family: “font”
  • Font-weight: the weight of a font
  • Font size: the size of a font
  • Font-style: normal

2. Text series attributes

  • Text-indent: indicates the indentation of text
  • Text-align: align text horizontally
  • Line-height: row height-word-spacing: spacing between words
  • Letter-spacing: The spacing between Chinese characters or letters
  • Text-transform: Uppercase, capitalize, capitalize
  • Color: text color

3. Element visibility:

  • Visibility: Control elements display hidden

4. List layout attributes:

  • List-style: indicates the list style, including list-style type and list-style image

5. Cursor properties: -cursor: What shape is the cursor displayed

React Native CSS styles?

React Native’s styles basically implement a subset of CSS. These style names follow the naming conventions of CSS on the Web, but use the hump naming conventions of JS syntax.

1. Inline styles: In general, inline styles are simple and crude, allowing you to debug quickly.

<Text style = {{fontSize:20,fontStyle:'normal',fontWeight:'bold'}}> test </Text>Copy the code

2. Object style: In contrast to the syntax of inline style, it is separated from the inline style to avoid creating styles every time the render method is used

const italic = {fontSize:20, fontStyle:'italic',fontWeight:'bold'}; < font style = {italic}>Copy the code

3. Use StyleSheet. Create: StyleSheet.

StyleSheet also helps you check that the style syntax makes sense. So it’s a good style choice

const styles = StyleSheet.create({font:{fontSize:20,fontStyle:'italic',fontWeight:'bold'},content:{backgroundColor:'#aaaaaa'}}); <Text style ={styles.font}> I am StyleSheet. Create create style </Text>Copy the code

4. Style splicing: The reuse of multiple styles by a component can use style splicing, which is a practical way to combine styles

const styles = StyleSheet.create({font: {fontSize:20,fontStyle:'italic',fontWeight:'bold'},content:{backgroundColor:'#aaaaaa'}}); < Text style = {[styles. The content and styles. The font]} > I am a combination style < / Text > < Text style = {[styles. The content and styles. The font, {color: '# 666666}]} > I am a combination style 2 < / Text >Copy the code
  1. Conditional styles: Styles components according to the rendering logic
<Text style = {this.state.toucher && styles.font}> I am conditional style </Text>Copy the code
  1. Use the parent class style to use the component style to pass, so that the parent component can control the flow and action style more effectively.
< img style = {this.props. Style}> </ img >Copy the code

RN uses JavaScript to write styles, all core components accept a property called style, and you can use any JS syntax to generate style objects as long as the end result is of the correct type

React Native uses the Flexbox rule by default to specify the layout of a component’s child elements.

What is the difference between writing the style tag after the body and before it

When the style element appears in the body element, the end result is the same as when the style element appears in the head element.

Page loading is top-down. Place the style tag before the body to load the style first. After the body tag, because the browser parses the HTML document line by line, parsing to the stylesheet written in the document will cause the browser to stop rendering, wait for the stylesheet to load and parse, possibly causing FOUC, redraw, or relayout

<link rel=stylesheet… > can appear in the body element. And may also cause the above problems. However, link is a reference resource, which means it can be used for intentional asynchronous loading. While the style element is directly embedded, there is no reasonable use case for it. So the HTML standard allows a link in a body, but not a style.

position:fixed; How to deal with invalid under the mobile terminal?

Fixed positioning is actually relative to the browser viewport to locate. Mobile browsers have two viewports: the visual viewport and the layout viewport.

When you slide across the screen you slide across the viewport, so the original page is still there and fixed has not changed position, but the fix element has moved position relative to the viewport.

If it’s fixed horizontally, it can go through

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"/>
Copy the code

To set the width of the page equal to the width of the screen, and not allow the user to zoom, of course, the design needs to adapt

The other is the vertical problem. In iOS, it is common to have fixed elements and input elements at the same time. For example, there is a fix footer at the bottom of the page, but the fixed element with a soft keyboard evokes a lot of confusing problems. For example, the page does not change, only the fix element changes position, breaking the overall layout.

This is also a visual viewport and layout viewport highly inconsistent problem, adjusting the page layout, set into the phone’s screen height body height, the page as a whole is rolling, rolling area package in child components, and adaptive height, so the outermost fix element in the keyboard jacking, page changes, equivalent to the browser height has changed.

What is reflux (rearrangement) and redraw and the difference

Backflow and redraw will affect page performance, and these two will be mentioned at the same time every time. The relationship is almost as close as the MC beside KFC.

When the page loads, the browser renders as follows:

  1. Parse HTML, generate DOM tree, parse CSS, generate CSSOM tree
  2. Combine DOM Tree and CSSOM Tree to generate Render Tree
  3. Layout(backflow): According to the generated rendering tree, backflow (Layout), get the geometry information of nodes (position, size)
  4. Painting(repainting): Get absolute pixels of nodes based on the rendered tree and geometry information from backflow
  5. Display: Send the pixel to the GPU and Display it on the page. (There is more to this step, such as merging multiple compositing layers into one layer on the GPU and displaying them on a page. The principle of CSS3 hardware acceleration is to create a composition layer.)

backflow

By constructing the render tree and combining the visible DOM nodes with their corresponding styles, it is necessary to calculate their exact position and size in the device viewport. This stage of calculation is called backflow. Each page needs to backflow at least once, even when the page is first loaded, which is bound to happen because the Render Tree is being built.

redraw

By constructing the render tree and the backflow stage, we determine the visible nodes, their styles and specific geometric information (location, size), and convert each node of the render tree into an actual pixel on the screen. This stage is called the redraw node.

Operations that cause backflow:

  • Page first render
  • The browser window size changed. Procedure
  • Changes in element size or position (including margins, inner borders, border size, height, width, etc.)
  • Element content changes (number of words or image size, such as when the user enters text in an input field, etc.)
  • Element font size changes
  • Add or removevisibletheDOMThe element
  • The activationCSSPseudo classes (e.g.: hover)
  • Query some properties or call some methods

What are the specific differences between inline elements and block-level elements? Are the padding and margin of the inline elements settable?

Block-level elements feature:

Always monopolize a line and appear to start on another line, and subsequent elements must also appear on another line;

Width, height, padding, and margin are all controllable;

Inline elements feature:

On the same line as the adjacent inline element;

The width, height, top/bottom of the inner margin, and top/bottom of the outer margin cannot be changed.

Browsers also default to inline-block elements that have built-in dimensions and can be set to height and width, but do not wrap. , ,

What is the cause of img image margins? How to solve it?

The gap at the bottom of the image actually refers to the layout model of the inline elements. The default vertical alignment of the image is the baseline, and the position of the baseline is font dependent. So at some point, the gap at the bottom of the image might be 2px, and at other times it might be 4px or more. Different font sizes should also affect the size of the gap.

  1. To a (row-level) block element
 display : block
Copy the code
  1. Float, float elements can be converted to block elements by default (width and height attributes can be set at will)
Float: left;Copy the code
  1. Define vertical-align for img (eliminate bottom margin)
img{    
    border: 0;    
    vertical-align: bottom;
}
Copy the code
  1. Set font size to 0 for its parent;

  2. Set the parent tag to the same height as the image

Talk about CSS cascading contexts

Most people, after learning CSS initially, have the impression that z-index is used to define the stack order of an element on the z-axis of the screen. For example, if A and B overlap, which is A little tedious to say,

  1. If pretty girl A overlaps with text B
  2. But when the page renders, the text is above the image, blocking your view of the girl
  3. At this point, you might
    • Set the girl’s Z-index to 999
    • Set the z-index of the text to -1

That’s the differential treatment. Since the above paragraph is taken as an example, it indicates that this understanding is problematic, or at least not rigorous.

  1. z-indexAttributes only inPositioning elements(to define thepositionProperty, and the value of the property is notstaticValue element) has an effect on.
  2. Elements in theThe Z axisThe stack order in which the element belongsCascading context, the elements of theCascading level, and the element inOrder in documentsAnd so onz-indexValue is just one of the conditions that determines the level of cascade of elements.

What is “Cascading Context”

Stacking context is a three-dimensional concept in HTML. It demarcates some kind of domain or scope, separates the inside from the outside at the level of rendering rules, and gives some characteristics to the elements themselves and their inner regions.

In the CSS2.1 specification, the position of each box model is three-dimensional, that is, in addition to the elements being tiled along the X and Y axes on the page, they also have a depth that is perpendicular to the screen, that is, the Z axis representing the cascade.

How to Create “Cascading Contexts” Cascading contexts are mostly created by a few specific CSS properties.

  • The root element in HTML itself has a cascading context, called a “root cascading context.”
  • The normal element sets position to a non-static value and z-index to a specific value, generating a cascading context. Css3 adds some conditions for creating a cascading context, as listed below.

Cascading order

Stacking order, which indicates the specific vertical display order in which elements are stacked, is a rule for determining the level of stacking of elements.

When elements overlap, it is necessary to decide which part of the content is displayed on the screen, so the cascading order determines a priority rule, also known as a hierarchy rule. The following rankings are ranked in descending order from top to bottom:

  1. Z-index > 0 (requires z-index to take effect)
  2. Z-index: auto or z-index: 0 (z-index: auto does not create a cascading context)
  3. Inline, inline-block inline boxes
  4. Float box
  5. Block a block-level box that is not inline-block and has no child element positioned in position (except static)
  6. z-index < 0
  7. Cascading context elementbackground/border

When elements are stacked, the coverage relationship generally follows the following two rules:

  1. In the same cascading context, when there is a distinct cascading level identifier, such as validz-indexValue, cascade level value the one with the big value overlays the one with the small value.
  2. When elements are cascaded at the same level and in the same order, the last element in the DOM flow overwrites the first.

For detailed explanation and case analysis, please refer to “CSS Cascading Context”

CSS percentage unit relative to baseline

When padding, margin, etc., is set to a percentage or negative value for a child element contained within the parent element, it is not the top margin relative to the height of the parent element, or the left margin relative to the width of the parent element.

  1. Width height percentage

When the height and width of an element are set to percentages, they are based on the height and width of the block-level object containing them, respectively. That’s what regular percentages mean.

  1. Margin percentagemarginThe percentage value of is calculated with reference to the width of the block it contains. When the writing mode becomes vertical, the reference will be changed to the height of the containing block.why

The definitive guide to CSS:

We believe that the normal flow of most elements will be high enough to contain the descendant elements (including from the outside), if an element of the up and down the outside is the height of the parent element percentage, can lead to an infinite loop, the parent element height increases, the increase of elements from the outside to adapt to the posterity, and accordingly, The upper and lower margins increase as the parent element height increases.

  1. The padding percentage is the same

  2. In standard box model, width: 100%; padding: 10% 10%; Box-sizing: border-box; width (); width (); width (); width (); width (); width (); width (); width (); width (); width ();

  3. Percentages are used in the Translate function based on the width and height of the element itself.

  4. Margin for the negative

    1. Negative margin – left margin – right
      • The element itself has no width and will increase its width
      • The element itself has a width, which causes displacement
    2. Margin-top is negative, regardless of whether the height is set, it will not increase the height, but will produce upward displacement
    3. When margin-bottom is negative, it does not shift and instead reduces its CSS reading height.
  5. Padding unfortunately, padding is not allowed to be negative and is invalid if it is

Specific interpretation and manual sample please click silly points not clear CSS | percentage (negative) benchmark is the length of the who

This article contains: a journey of large front end foundation building from scratch (simple and profound, constantly updated ~)

Reference Documents:

  1. The CSS priority and its calculation method
  2. CSS chapter – nearly 20,000 words to help you consolidate CSS knowledge
  3. Float principle and clear float
  4. How does the browser determine if an element matches a CSS selector
  5. What properties of CSS can be inherited?
  6. React-native style Settings
  7. Fixed element soft keyboard arouses fixed element failure solution for ios layout on web side
  8. CSS classic interview questions