Basic JavaScript

Time:2022-2-17

1. CSS box model and weird box model

1、**Standard box modelinwidthRefers to the content areacontentWidth of the;heightRefers to the content areacontentThe height of the.

Size of box under standard box model = content + border + padding + margin

Basic JavaScript

2、Weird box modelMediumwidthThe width of border and padding refers to the total width of border and padding;heightIt refers to the total height of content, border and inner margin

Size of box in weird box model = width (content + border + padding) + margin

3. Which box model to use in IE8 + browser can be triggered by box sizing (a new attribute in CSS),

The default value is content box, which is the standard box model; If box sizing is set to border box, the IE box model is used

4、box-shadow: h-shadow v-shadow blur spread color inset;

H-shadow and v-shadow must be. Position of horizontal and vertical shadows. Assignment is allowed. Blur optional, blur distance. Spread optional, the size of the shadow. Color optional, the color of the shadow. Inset optional. Change the outer shadow to the inner shadow.

2. New features of HTML5 in tags, attributes, storage and APIs

• label:

Add semantic tags(aside / figure / section / header / footer / navEtc.),

Add multimedia Tagsvideoandaudio, which makes the style and structure more separated

• properties:

Enhanced forms, mainly enhancedinputType attribute of;

metaAdd charset to set the character set;

scriptAdd async to load scripts asynchronously

• storage: increaselocalStoragesessionStorageandindexedDB, introducedapplication cacheCaching web and Applications

• API: addDrag and drop APIGeographic locationSvg drawingCanvas drawingWeb WorkerWebSocket

3. CSS3 animation

1: Transition animation — transitions

1: Transition animation transitions

meaning: in CSS3, the transitions function realizes the animation function by smoothly transiting an attribute of an element from one attribute value to another within a specified time.

The transitions attribute is used as follows:

transition: property | duration | timing-function | delay

transition-property:Represents a smooth transition to that attribute.

transition-duration:Indicates how long it takes to complete the smooth transition of attribute values.

transition-timing-functionIndicates how to smooth the transition.

linear Specifies the transition effect from beginning to end at the same speed (equal to cubic Bezier (0,0,1,1)).
ease Specify the transition effect of starting slowly, then getting faster, and then ending slowly (cubic Bezier (0.25,0.1,0.25,1)).
ease-in Specifies the transition effect starting at a slow speed (equal to cubic Bezier (0.42,0,1,1)).
ease-out Specifies the transition effect ending at a slow speed (equal to cubic Bezier (0,0,0.58,1)).
ease-in-out Specifies the transition effect starting and ending at a slow speed (equal to cubic Bezier (0.42,0,0.58,1)).
cubic-bezier(n,n,n,n) Define your own value in the cubic Bezier function. Possible values are values between 0 and 1.

transition-delay:Defines how long the transition animation is delayed.

The default value is all 0 ease 0

Browser support:Ie10, Firefox 4 +, Opera 10 +, Safari 3 + and chrome 8+

The following is a demo of the transitions transition function:

The HTML code is as follows:

< div class = "transitions" > transitions transition function < / div >

The CSS code is as follows:

.transitions {
    -webkit-transition: background-color 1s ease-out;
    -moz-transition: background-color 1s ease-out;
    -o-transition: background-color 1s ease-out;
}.transitions:hover {
    background-color: #00ffff;
}

The effect is as follows:

Transitions transition function

If you want to transition multiple attributes, you can use comma separation, as shown in the following code:

div { -webkit-transition: background-color 1s linear, color 1s linear, width 1s linear;}

2. We can use the transitions function to smoothly transition multiple attribute values at the same time.

The following HTML code:

<h2>Transitions smooth transition multiple attribute values < / H2 > < div class = "transitions2" > transitions smooth transition multiple attribute values < / div >

CSS code is as follows:

.transitions2 {
        background-color:#ffff00;
        color:#000000;
        width:300px;
        -webkit-transition: background-color 1s linear, color 1s linear, width 1s linear;
        -moz-transition: background-color 1s linear, color 1s linear, width 1s linear;
        -o-transition: background-color 1s linear, color 1s linear, width 1s linear;
}.transitions2:hover {
        background-color: #003366;
        color: #ffffff;
        width:400px;
}

The effect is as follows:

Transitions smoothes the transition of multiple attribute values

Transitions smoothes the transition of multiple attribute values

be careful:Transition timing function indicates what method is used for smooth transition. Its values are as follows:

There is ease | linear | ease in | ease out | ease in out | cubic Bezier

For now, we can understand that c-out and so on can be ignoredmeaning

ease:First fast and then slow down;

ease-in:Slow before fast

easy-out:Fast before slow

easy-in-out:Slow first, then fast, then slow

Understand the above attribute values, as shown in the following Demo:

The HTML code is as follows:

<div id="transBox" class="trans_box">
    <div class="trans_list ease">ease</div>
    <div class="trans_list ease_in">ease-in</div>
    <div class="trans_list ease_out">ease-out</div>
    <div class="trans_list ease_in_out">ease-in-out</div>
    <div class="trans_list linear">linear</div></div>

The CSS code is as follows:

.trans_box {
    background-color: #f0f3f9;  width:100%
}.trans_list {
    width: 30%;
    height: 50px;
    margin:10px 0;
    background-color:blue;
    color:#fff;
    text-align:center;
}.ease {
    -webkit-transition: all 4s ease;
    -moz-transition: all 4s ease;
    -o-transition: all 4s ease;
    transition: all 4s ease;
}.ease_in {
    -webkit-transition: all 4s ease-in;
    -moz-transition: all 4s ease-in;
    -o-transition: all 4s ease-in;
    transition: all 4s ease-in;
}.ease_out {
    -webkit-transition: all 4s ease-out;
    -moz-transition: all 4s ease-out;
    -o-transition: all 4s ease-out;
    transition: all 4s ease-out;
}.ease_in_out {
    -webkit-transition: all 4s ease-in-out;
    -moz-transition: all 4s ease-in-out;
    -o-transition: all 4s ease-in-out;
    transition: all 4s ease-in-out;
}.linear {
    -webkit-transition: all 4s linear;
    -moz-transition: all 4s linear;
    -o-transition: all 4s linear;
    transition: all 4s linear;
}.trans_box:hover .trans_list{
    margin-left:90%;
    background-color:#beceeb;
    color:#333;
    -webkit-border-radius:25px;
    -moz-border-radius:25px;
    -o-border-radius:25px;
    border-radius:25px;
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
}

The effect is as follows:

ease

ease-in

ease-out

ease-in-out

linear

2: Animations function: define multiple keyframes

The animations function is the same as the transitions function, which realizes the animation effect by changing the attribute value of the element.

The difference between them is that the transition function can only be used by specifying the start value and end value of the attribute. Then the animation effect is realized by smooth transition between the two attribute values, so the complex animation effect cannot be realized;

Animations achieves more complex animation effects by defining multiple keyframes and defining the attribute values of the elements in each keyframe.

Syntax:animations: name duration timing-function iteration-count;

Name: key frame set name (set of keys created by this name)

Duration: indicates how long it takes to complete the smooth transition of attribute values

Timing function: indicates the method of smooth transition

Iteration count: the number of iteration cycles. It can be set to a specific value or set to infinite for infinite loop. The default is 1

Usage:@-WebKit keyframes collection name of key frames {code for creating key frames}

As shown in the following code:

@-webkit-keyframes mycolor {
   0% {background-color:red;}
   40% {background-color:darkblue;}
   70% {background-color: yellow;}
   100% {background-color:red;}}
.animate:hover {
   -webkit-animation-name: mycolor;
   -webkit-animation-duration: 5s;
   -webkit-animation-timing-function:

4. Flex layout

After setting as flex layout, the of child elementsfloatclearandvertical-alignProperty will be invalidated.

Elements with flex layout are called flex containers

  • flex-direction
  • flex-wrap
  • flex-flow
  • justify-content
  • align-items
  • align-content

4.1.1 flex direction attribute

flex-directionProperty determines the direction of the spindle (that is, the arrangement direction of items).

.box {
flex-direction: row | row-reverse | column | column-reverse;
}

Basic JavaScript

It may have four values.

  • row(default): the main axis is horizontal and the starting point is at the left end.
  • row-reverse: the spindle is horizontal and the starting point is at the right end.
  • column: the main axis is vertical and the starting point is on the top edge.
  • column-reverse: the main axis is vertical and the starting point is at the lower edge.

4.1.2 flex wrap attribute

By default, items are arranged on a single line, also known as a grid line.flex-wrapProperty defines how to wrap a line if an axis cannot be arranged.

Basic JavaScript

.box{
flex-wrap: nowrap | wrap | wrap-reverse;
}

It may take three values.

(1)nowrap(default): no line breaks.

Basic JavaScript

(2)wrap: wrap, first line above.

Basic JavaScript

(3)wrap-reverse: wrap, first line below.

Basic JavaScript

4.1.3 flex-flow

flex-flowAttribute isflex-directionProperties andflex-wrapAttribute. The default value isrow nowrap

.box {
flex-flow: <flex-direction> || <flex-wrap>;
}

4.1.4 justify content attribute

justify-contentProperty defines the alignment of the item on the spindle.

.box {
justify-content: flex-start | flex-end | center | space-between | space-around;
}

Basic JavaScript

It may take five values, and the specific alignment is related to the direction of the axis. Let’s assume that the spindle is from left to right.

  • flex-start(default): align left
  • flex-end: align right
  • center: Centered
  • space-between: both ends are aligned, and the spacing between items is equal.
  • space-around: equal spacing on both sides of each item. Therefore, the interval between items is twice as large as that between items and borders.

4.1.5 align items attribute

align-itemsProperty defines how items are aligned on the cross axis.

.box {
align-items: flex-start | flex-end | center | baseline | stretch;
}

Basic JavaScript

It may take five values. The specific alignment is related to the direction of the cross axis. It is assumed that the cross axis is from top to bottom.

  • flex-start: align the start point of the cross axis.
  • flex-end: align the ends of the cross axes.
  • center: align the midpoint of the cross axis.
  • baseline: the baseline alignment of the first line of text of the item.
  • stretch(default): if the item is not set to height or set to auto, it will occupy the height of the whole container.

4.1.6 align content attribute

align-contentProperty defines the alignment of multiple grid lines. This property has no effect if the project has only one axis.

.box {
align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}

Basic JavaScript

This attribute may take 6 values.

  • flex-start: align with the start point of the cross axis.
  • flex-end: align with the end of the cross axis.
  • center: align with the midpoint of the cross axis.
  • space-between: align with both ends of the cross axis, and the spacing between the axes is evenly distributed.
  • space-around: the spacing on both sides of each axis is equal. Therefore, the spacing between the axes is twice as large as that between the axis and the frame.
  • stretch(default): the axis occupies the entire cross axis.

2、 Properties of the project

The following six properties are set on the project.

  • order
  • flex-grow
  • flex-shrink
  • flex-basis
  • flex
  • align-self

4.2.1 order attribute: defines the order of items 0

orderProperty defines the order in which items are arranged. The smaller the value, the higher the arrangement. The default value is 0.

.item {
order: <integer>;
}

Basic JavaScript

4.2.2 flex growth attribute: defines the magnification of the item 0

flex-growProperty defines the magnification of the item. The default is0That is, if there is no space left, it is also enlarged.

.item {
flex-grow: <number>; /* default 0 */
}

Basic JavaScript

If all itemsflex-growIf the attributes are all 1, they will equally divide the remaining space, if any. If a projectflex-growIf the attribute is 2 and all other items are 1, the remaining space occupied by the former will be twice that of other items.

4.2.3 flex shrink attribute: defines the reduction scale of the project 1

flex-shrinkProperty defines the reduction scale of the item. The default is 1, that is, if there is insufficient space, the item will be reduced.

.item {
flex-shrink: <number>; /* default 1 */
}

Basic JavaScript

If all itemsflex-shrinkThe attributes are all 1. When the space is insufficient, it will be reduced in equal proportion. If a projectflex-shrinkIf the property is 0 and other items are 1, the former will not shrink when the space is insufficient.

Negative values are not valid for this property.

4.2.4 the flex basis attribute will occupy a fixed space

flex-basisProperty defines the main size occupied by the project before allocating extra space. Based on this attribute, the browser calculates whether the spindle has excess space. Its default value isauto, that is, the original size of the project.

.item {
flex-basis: <length> | auto; /* default auto */
}

It can be set to followwidthorheightProperty (for example, 350px), the item will occupy a fixed space.

4.2.5 flex properties

flexAttribute isflex-grow, flex-shrinkandflex-basisThe default value is0 1 auto。 The last two properties are optional.

.item {
flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
}

This property has two quick values:auto (1 1 auto)And none(0 0 auto)。

It is recommended to use this attribute first rather than write three separate attributes separately, because the browser will calculate the relevant values.

4.2.6 align self attribute

align-selfProperty allows a single item to have a different alignment from other items and can be overwrittenalign-itemsProperties. The default value isauto, which means inheriting the parent elementalign-itemsProperty. If there is no parent element, it is equivalent tostretch

.item {
align-self: auto | flex-start | flex-end | center | baseline | stretch;
}

Basic JavaScript

This attribute may take six values. Except auto, all other values are completely consistent with the align items attribute.

5. Realize the horizontal and vertical center of an element

1) Disadvantages: if you don’t know the width and height, this effect can’t be achieved. If the data can not be divided, there is error in the effect.

{width:200px;
height:200px; Position: absolute or fixed;
top:50%;
margin-top:-100px; 
left:50%;
margin-left:-100px;}

2) Disadvantages: it is not suitable for elements with unknown width and height to be centered horizontally and vertically

{width:333px; 
height:333px; 
position:fixed;
margin:auto;
top:0; 
left:0; 
right:0; 
bottom:0;}

3) Advantages: it can realize the horizontal and vertical centering of an element with unknown width and height. Disadvantages: display: Flex; CSS3 newly added; Compatible with ie10 or above

html{ height:100%;} 

body{ margin:0; display:flex; height:100%;}

div{ margin:auto;}

Where: display: the nearest parent element given by flex

4)

body{ margin:0;}

div{
     position:fixed;
     top:50%; 
     left:50%; 
     transform:translate(-50%,-50%);
     }
     
 /*top:50%;  left:50%;  This is half the overall width and height of the browser viewport; 

transform:translate(-50%,-50%); Is half the width and height of the current element*/

6、BFC

Elements with BFC characteristics can be regarded as isolated independent containers, and the elements in the container will not affect the external elements in layout

The BFC characteristic can be triggered as long as the element meets any of the following conditions:

  • HTML root element
  • Floating element: float values other than none
  • Absolute positioning element: position (absolute, fixed)
  • Display is inline block and flex
  • Overflow values other than visible (hidden, auto, scroll)

The best way to establish BFC is overflow: hidden

Characteristics and application of BFC

1. When the elements are in the same BFC, the margins in the vertical direction will overlap. The solution is to put them in different BFC containers.

2. BFC can contain floating elements (clear floating), as long as the container overflow: hidden is set

3. BFC can prevent elements from being overwritten by floating elements (text wrapping problem), as long as the element overflow: hidden is set

7. Clear float

In the document flow, the height of the parent element is supported by the child element by default, that is, how high the child element is, how high the parent element is. However, when the child element is set to float, the child element will be completely separated from the document flow. At this time, the child element will not be able to support the height of the parent element, resulting in the height collapse of the parent element.

Solution 1: after + zoom (the best to use, the most recommended, and the compatibility is also very good)

Parent element:: after {content: ”; display: block; height: 0; visibility: hidden; clear: both;}

Parent element: {zoom: 1}

Suggestion: define public classes to reduce CSS code

Solution 2: add the declaration overflow: hidden to the parent element; zoom:1; (need to be compatible with IE6)

Advantages: simple, less code and good browser support

Disadvantages: it cannot be used with position, because the exceeding size will be hidden**

8. Processing browser compatible

Style compatibility (CSS)

Basic JavaScript

Interactive compatibility (JavaScript)

Basic JavaScript

1. For the problem of event compatibility, we usually need to encapsulate the method of an adapter to filter event handle binding, removal, bubble blocking and default event behavior processing

var  helper = {}

 //Binding event
 helper.on = function(target, type, handler) {
     if(target.addEventListener) {
         target.addEventListener(type, handler, false);
     } else {
         target.attachEvent("on" + type,
             function(event) {
                 return handler.call(target, event);
             }, false);
     }
 };

 //Cancel event listening
 helper.remove = function(target, type, handler) {
     if(target.removeEventListener) {
         target.removeEventListener(type, handler);
     } else {
         target.detachEvent("on" + type,
         function(event) {
             return handler.call(target, event);
         }, true);
     }
 };
Copy code

Browser hack

Basic JavaScript

1、 Browser compatibility summary

**
**1. Double floating margin:
Reason: multiple parallel floating elements have set the left or right boundary value (x), and the left or right boundary value of the first floating element under IE6 is 2 times (2x);
Solution: add display: inline for the first floating element; Style;

2. Height not adaptive:
Reason: the parent height of multiple parallel floating elements cannot be extended.
Solution: add < div class = “clear” > < / div > after the last floating element clear {clear:both;}

3. The upper and lower boundaries are not recognized:
Cause: the parent element does not specify the height, and the margin top and margin bottom parsing errors
Solution: add style: overflow: Auto on the parent element of this element; display:inline-block;
Note: when the element is set to inline block, finally specify the width for the element;

4. IE6 does not recognize micro height:
Reason: IE6 cannot recognize the height lower than the current word height
Solution: set font size: 0 / overflow: hidden for this element;

5. IE6 link pseudo class problem:
Reason: IE6 does not recognize P: hover, but only a: hover
Solution: replace it with a: hover.

6. IE6 and 7 ladder list problems:
Reason: floating element does not specify width;
Solution: specify a fixed width for the floating element

2、 Compatible (hack) technology

**
**1. Attribute filtering

#nav {
_ margin:100px; /* IE6 only*/
*margin:100px; /* Only IE6 and IE7 are recognized*/
margin:100px
#nav {
_ margin:100px; /* IE6 only*/
*margin:100px; /* Only IE6 and IE7 are recognized*/
margin:100px\0/; /* IE8 only*/
\9{IE6-10}
}
/; /* IE8 only*/ {IE6-10} }

2. Selector filtering:

* html #nav {margin:10px; border:1px #f00 solid;} /* IE6 recognition only*/
*+html #nav {margin:100px; border:1px #f00 solid;} /* IE7 recognition only*/
/*For Firefox*/
@-moz-document url-prefix() {
#nav{ width:200px; }
}
/*For Safari & Chrome*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
#nav{ width:300px; }
}

Note: as for the unrecognized font size below 12 in chrome Chinese version, the solution is to set the style as follows:

html {-webkit-text-size-adjust:none;}
/*For opera*/
@media all and (-webkit-min-device-pixel-ratio:10000), not all and (-webkit-min-device-pixel-ratio:0) {
#nav{ width:400px; }
}

3. Style sheet filtering

<!-- [if IE 6] > only HTML recognized by IE6 <! [endif]-->
<!-- [if LT IE 6] > less than the HTML recognized by IE6 <! [endif]-->
<!-- [if GT IE 6] > greater than HTML recognized by IE6 <! [endif]-->
<!-- [if ie] > only HTML recognized by IE <! [endif]-->
<!-- [if LTE IE 6] > HTML recognized less than or equal to IE6 <! [endif]-->
<!-- [if GTE IE 6] > HTML recognized by IE6 <! [endif]-->

3、 Precautions

**Remember to clear the float. (add clear float at the bottom of the container with float element)
Try to give floating elements a definite width.
Try to use padding instead of margin.
If there are both float and margin, add display: inline.
Try to avoid using absolute positioning for layout; If used, specify Z-index, top, left;
Try to avoid using translucent PNG pictures (png-24); If used, repair it with PNG patch;
If the width is stretched, set overflow: hidden;
In case of inexplicable padding, set font size: 0 and overflow: hidden;

4、 Other skills

1. Setting padding for div in Firefox will increase width and height, but ie will not (can be solved with! Important)
2. Centering problem

a). Center vertically Set the line height to the same height as the current div, and then use vertical align: middle (be careful not to wrap the content.)
b). Center horizontally margin: 0 auto; (of course not everything)

3. If you need to add a style to the contents of a tag, you need to set display: block; (common in navigation tabs)
4. The difference between FF and IE’s understanding of box leads to the difference of 2px, and the double margin of div set as float under ie
5. UL tag has list style and padding under FF by default It’s best to make a statement in advance to avoid unnecessary trouble (common in navigation tabs and content lists)
6. As an external wrapper, do not set the dead height of div, and it is better to add overflow: hidden To achieve a high degree of adaptation
7. About hand cursor cursor: pointer. Hand is only applicable to ie

9. Compatibility of different resolutions

I Load different CSS style files according to different resolutions

The idea of this method is to create different CSS files for 800, 1280, 1440, 1600, 1920 and other resolutions. Then write CSS style sheets at various resolutions. You may feel that writing so many different CSS style sheets for a page must be a lot of work. In fact, not necessarily. According to my practice in this project, I found that the workload is actually relatively small.

First of all, when we are working on a project, we usually have some range restrictions. For example, this project only needs to adapt to 1280 ~ 1920 resolution. And between the resolutions, sometimes we just adjust the width, height, size and position of the elements on the page. The overall framework is similar or the same.

Not only that, sometimes the requirements of the project are not high and the design draft is not restored by comparing the height of 1:1. At this time, our style sheet at 1440 resolution is also practical at 1280 resolution. At this time, our workload is further reduced.

At this time, we can first complete the CSS style sheet under a resolution. Then, on this basis, adjust other resolutions. In this process, we only need to adjust some parameters.

For example, in my project, I only made three style sheets for different resolutions

style sheet

At this time, we only need to be on our HTML pageIn the tag, use js to load different CSS style sheets according to different computer resolutions** Note that the JS here must be written inTag, so you can load the CSS style sheet in advance before loading the page content**

<script>
    //Call this CSS when the resolution is greater than or equal to 1680, mostly 1920
    if(window.screen.width >= 1680){
        document.write('<link rel="stylesheet" href="css/index_1920.css">');
    }
    //When the resolution is 1600-1680, call this CSS
    else if(window.screen.width >= 1600){
        document.write('<link rel="stylesheet" href="css/index_1600.css">');
    }
    //Call this CSS when the resolution is less than 1600
    else{
        document.write('<link rel="stylesheet" href="css/index.css">');
    }
</script>

In this way, you can use different CSS style sheets according to the resolution of different computers. This completes the page using different resolutions.

II Using media query

Media query is a new feature of CSS3, which is compatible with most browsers. The idea of this method is to apply different CSS styles according to different resolutions.

This idea is similar to method 1, or the idea of method 1 is similar to this idea. After all, this is also an official practice. We have two ways to use media query.

Summary of all media parameters

Width: the visual width of the browser.
Height: the visual height of the browser.
Device width: the width of the device screen.
Device height: the height of the device screen.
Orientation: whether the detection equipment is in the horizontal or vertical state at present.
Aspect ratio: detect the proportion of the browser’s visual width and height. (for example: aspect ratio: 16 / 9)
Device aspect ratio: measure the ratio of the width and height of the device.
Color: the number of bits to detect the color. (for example, min color: 32 will detect whether the device has 32-bit color)
Color index: check the color in the device color index table. Its value cannot be negative.
Monochrome: detects the number of bits per pixel in the monochrome frame buffer. (this is too advanced. I guess we seldom use it)
Resolution: detects the resolution of the screen or printer. (for example: Min resolution: 300dpi or min resolution: 118dpcm).
Grid: detect whether the output device is a grid device or a bitmap device.

1. Introduce different CSS style sheets according to different resolutions

This method is the same as method 1. It also introduces the corresponding CSS style sheet by judging the resolution of the computer.

<!--  The resolution is lower than 1280, and test-01 is adopted CSS style sheet -- >
<link rel="stylesheet" media="screen and (max-device-width:1280px)" href="test-01.css">
<!--  The resolution is higher than 1400, and test-02 is adopted CSS style sheet -- >
<link rel="stylesheet" media="screen and (min-device-width:1440px)" href="test-02.css">
2. In the same CSS style sheet, write different CSS styles according to different resolutions

This method has only one CSS demo table, in which different CSS styles are written according to different resolutions.

<style media="screen">
    /*If the resolution is lower than 1280, use the following style*/
    @media screen and (max-device-width:1280px){
        div{
            width: 200px;
            height: 200px;
            background-color: green;
        }
    }
    
    /*The resolution is higher than 1440, and the following style is adopted*/
    @media screen and (min-device-width: 1440px){
        div{
            width: 300px;
            height: 300px;
            background-color: red;
        }
    }
</style>

PC side page adaptation

Take the width of design drawing 1920 as an example:
There is a unit called VW in CSS, which is a percentage unit based on the width of the browser. The difference from% is that the child element% is calculated relative to the width of the parent element, while VW is calculated according to the width of the browser. For example, the browser width is 1920px, the parent element width is 100px, and the child element width written at 50% is 50px; If the child element is written 50Vw, its width is 50% of the browser width, i.e. 960px;

After making this clear, we can calculate:
100vw = 1920px;
1vw = 19.2px
1px = 1 / 19.2vw;

Thus, we can set the variable @1px: 1 / 19.2vw;

In this way, when writing styles, you can use @1px for calculation, as shown in the figure:

Basic JavaScript

In this way, if the browser size changes, the corresponding VW value will also change, and naturally the PX calculated by VW will also change, so as to achieve the purpose of being compatible with all kinds of browsers;
However, the drawback of this method is that when the browser width becomes smaller and smaller, the margin padding equivalent will become smaller and smaller, and the minimum font is 12px, so the elements will be crowded together when it is about 800px. Although we don’t need to be compatible with 800 resolution PC now, generally the minimum compatibility is 1200, but in order to be rigorous, Is it compatible with the media below 1200

Of course, it doesn’t mean rewriting the element attribute value according to the 1200 design drawing

a key
1200 / 1920 = 0.625
We know the ratio of the two. At this time, we can set a variable, which can also be called a constant, because at this time, we need to set a fixed value

Because it is based on the 1920 design drawing, we set each 1px under 1200 as 0.625px of 1920;

@1200-1px : 0.625px

Write at this time
@media screen and(max-width:1201){
Copy the above CSS code and replace @ 1px globally with @ 1200-1px;
}
As shown in the figure:

Basic JavaScript

 Layout scheme of mobile terminal

1. Use media query + REM unit

2. Layout using VW units + REM units

3. Use js + REM unit layout

4. Use sass + VW unit layout

  1. Use media query + REM unit

Principle: use the characteristics of the media query detection device to change the font size of the root node according to the device

Implementation steps:

  (1) Change the font size of the root node through media query

@media all and (min-width: 320px) {
     html {
            font-size: 32px;
        }
}
@media all and (min-width: 375px){
    html{
        font-size: 37.5px;
    }
}

  (2) The layout of elements in the page is in rem units, which can achieve the adaptive state

div {
    width: 10rem;
    height: 100px;
    background: red;
}

Disadvantages: it cannot be finely adapted to each device, and the amount of code is large

  2. Layout using VW units + REM units

Principle: when the screen size changes, the value of VW as the unit will also change. VW is used as the unit of font size of the root node. Therefore, in different screen sizes or devices, the value of font size of the root node is different, and the value of REM unit is different

  Implementation steps:

(1) Use VW unit as the unit of HTML font size (calculation)

//If the design drawing is 750px, we need to set the code

  html{

  font-size: 13.33333333vw

  }

(2) All page layouts use REM units

  div{

//In this way, 1rem is the 100px on the design draft

width:1rem; // The value displayed in the page is 50px

  height:1rem;

  }

Question: why is the font size of the root node 13.33333vw and why is 100px = 1rem?

  750px = 100vw

  1px = 100 / 750 = 0.133333333333333vw

  100px = 0.133333333333333vw *100px = 13.33333333vw

The value of REM is calculated according to the font size of the root node. The font size of the root node is set to 100px to facilitate calculation

The final result is 100px = 1rem

  3. Use js + REM unit layout

Principle: get the width of the device through JS to calculate the font size of the root node. The value obtained by rem is different, and it can be adapted to different pages

We can install an extension in the editor to automatically calculate PX – > rem

(1) Install the plug-in in vscode extension: cssrem

(2) Then change in the vscode configuration file: rootfootprint is the number of design drawing / 10

(3) Use the script tag in the page to introduce and obtain the characteristics of the device and change the JS file of the geological body size of the root node

(4) All layouts in the page use rem as the unit. You can write as much as the value at the design drawing quantity, but you should choose the value converted to rem

  4. Use sass + VW unit layout

Principle: use VW as the layout unit of all elements of the page to simplify the layout combined with REM + VW

  (1) Functions using sass:

@function vw($px) {
    @Return ($PX / width of design drawing) * 100vw;
}

  (2) Layout in page

header {
     Height: VW (measured value);
      background: green;
      font-size: vw(48);
}

postcss-px-to-viewport

10. CSS selector

Classification and priority of selectors

Basic JavaScript

  • Label selector: priority weighted value is 1.
  • Pseudo element or pseudo object selector: priority weighted value is 1.
  • Class selector: priority weighted value is 10.
  • Attribute selector: priority weighted value is 10.
  • ID selector: priority weighted value is 100.
  • Other selectors: priority weighted value is 0, such as universal selector, etc.

Then, take the above weighted values as the starting point to calculate the total weighted values of selectors in each style. The calculation rules are as follows:

  • Count the number of ID selectors in the selector and multiply by 100.
  • Count the number of class selectors in the selector and multiply by 10.
  • Count the number of label selectors in the selector and multiply by 1.

By analogy with this method, finally add all the weighted values to get the total weighted value of the current selector, and finally decide which style has the highest priority according to the weighted value.

Difference between import and @ link

There are three main ways to use CSS in the page: adding and defining style attribute values in the line, embedded calls in the page header and external link calls, of which there are two kinds of external references: link and @ import. There are two ways to externally reference CSS: link and @ import:

XML / HTML code
< link rel = "stylesheet" Rev = "stylesheet" href = "CSS file" type = "text / CSS" media = "all" / >  
XML / HTML code
<style type="text/css" media="screen">  
@Import URL ("CSS file");  
</style>

Both of them refer to CSS externally, but there are some differences:

Difference 1: link is an XHTML tag. In addition to loading CSS, it can also define RSS and other [email protected] Import belongs to the category of CSS. You can only load CSS

Difference 2: when link references CSS, it is loaded at the same time when the page is [email protected] Import requires the page to be loaded after the page is fully loaded.

Difference 3: link is an XHTML tag, and there is no compatibility [email protected] Import is in CSS2 1, which is not supported by lower versions of browsers.

Difference 4: link supports using JavaScript to control DOM to change style; @ import is not supported.

Supplement: @ import optimal writing method
@Import is generally written in the following ways:

@import 'style. CSS' // windows IE4 / NS4, Mac OS X IE5, Macintosh IE4 / IE5 / NS4 not recognized
@Import "style. CSS" // windows IE4 / NS4, Macintosh IE4 / NS4 not recognized
@Import URL (style. CSS) // windows NS4, not recognized by Macintosh NS4
@Import URL ('style. CSS') // not recognized by windows NS4, Mac OS X IE5, Macintosh IE4 / IE5 / NS4
@Import URL ("style. CSS") // windows NS4, not recognized by Macintosh NS4

According to the above analysis, @ import URL (style. CSS) and @ import URL (“style. CSS”) are the best choices, with the most compatible browsers.

From the perspective of byte optimization, @ import URL (style. CSS) is the most recommended

11. Draw a line of one pixel

Set media query + transfrom Scaley and border on canvas, height, HR and pseudo elements

ctx.lineWidth = 1; 
ctx.beginPath(); 
ctx.moveTo(10, 100); 
ctx.lineTo(300,100); 
ctx.stroke(); 

12. Gets the width and height of the DOM element

1、Element.style.width/height

Only inline styles can be obtained

var ele = document.getElementById('element');
console.log(ele.style.height); // '100px'

2、window.getComputedStyle(ele).width/height

IE9 and above can obtain real-time information

var ele = document.getElementById('element');
console.log(window.getComputedStyle(ele).width); // '100px'
console.log(window.getComputedStyle(ele).height); // '100px'

3、Element.currentStyle.width/height

The function is the same as the second point. It only exists in the old version of IE (below IE9). Don’t use it unless it is compatible with the old version of IE.

4、Element.getBoundingClientRect().width/height

In addition to obtaining width and height, it can also obtain information such as element position

var ele = document.getElementById('element');
console.log(ele.getBoundingClientRect().width); // 100
console.log(ele.getBoundingClientRect().height); // 100