link vs @import

  • Link belongs to the XHTML tag, while@importCSS provides this.
  • When the page is loaded, link is loaded at the same time, and@importReferenced CSS will wait until the page is loaded.
  • Import is only recognized in IE 5 or higher, while link is an XHTML tag with no compatibility issues.
  • Link mode has a higher style weight than@importThe weight.
  • Differences when using DOM to control styles. When using javascript to control the DOM to change styles, you can only use the link tag because@importIt’s not dom control.

CSS Hardware Acceleration

CSS hardware acceleration refers to handing over the browser’s rendering process to the GPU, rather than using its own slower renderer, which makes animation and transition smoother

To turn on hardware acceleration, use a specific CSS statement:

/** Use 3d effects to enable hardware acceleration **/
.speed-up {
    -webkit-transform: translate3d(250px.250px.250px) rotate3d(250px.250px.250px, -120deg) scale3d(0.5.0.5.0.5);
}
Copy the code

If you don’t need to use the transform and just turn on hardware acceleration, you can write:

/** In principle, hardware acceleration is enabled using 3d effects **/
.speed-up {
    -webkit-transform: translateZ(0);
    -moz-transform: translateZ(0);
    -ms-transform: translateZ(0);
    -o-transform: translateZ(0);
    transform: translateZ(0);
}
Copy the code

For Safari and Chrome, there may be flickering problems with animation or Transition. You can use this method to resolve the problem:

.speed-up {
    -webkit-backface-visibility: hidden;
    -moz-backface-visibility: hidden;
    -ms-backface-visibility: hidden;
    backface-visibility: hidden;

    -webkit-perspective: 1000;
    -moz-perspective: 1000;
    -ms-perspective: 1000;
    perspective: 1000;

    /** WebKit can also use the following statement **/
    -webkit-transform: translate3d(0.0.0);
    -moz-transform: translate3d(0.0.0);
    -ms-transform: translate3d(0.0.0);
    transform: translate3d(0.0.0);
}
Copy the code

Note: Hardware acceleration is best used only on animation or Transform. Don’t abuse hardware acceleration, as this can add to performance, and if you abuse it, it will make the animation more sluggish, which is not worth the cost.

Mobile 1px problem

Mobile devices have one parameter: devicePixelRatio (DPR), which is the ratio of device pixels to CSS pixels when the default zoom is 100%.

window.devicePixelRatio = 'Physical pixel /CSS pixel'
Copy the code

The current mainstream screen DRP is either 2(Iphone 8) or 3(Iphone 8 Plus).

The solution

1. WWDC’s solution for IOS: Reduce the value

border:0.5 px. solid #E5E5E5
Copy the code
  • Advantages: Simple, no side effects
  • Cons: supports IOS8+

2. Use border images

border: 1px solid transparent;
border-image: url('. /.. /.. /image/96.jpg') 2 repeat;
Copy the code
  • Advantages: No side effects
  • Disadvantages: Not flexible enough, poor performance

3. Use the box – shadow

box-shadow: 0  -1px 1px -1px #e5e5e5// Top edge1px  0  1px -1px #e5e5e5// The right line0  1px  1px -1px #e5e5e5, // lower sideline -1px 0  1px -1px #e5e5e5; / / the left lineCopy the code

4. Use pseudo-elements

  1. A border
.setOnePx{
  position: relative;
  &::after{
    position: absolute;
    content: ' ';
    background-color: #e5e5e5;
    display: block;
    width: 100%;
    height: 1px; /*no*/
    transform: scale(1.0.5);
    top: 0;
    left: 0; }}Copy the code
  1. Article 4 the border:
.setBorderAll{
     position: relative;
       &:after{
           content:"";
           position:absolute;
           top: 0;
           left: 0;
           width: 200%;
           height: 200%;
           transform: scale(0.5);
           transform-origin: left top;
           box-sizing: border-box;
           border: 1px solid #E5E5E5;
           border-radius: 4px; }}Copy the code
  • Advantages: Good compatibility
  • Cons: Style influences need to be considered

5. Set the viewport scale

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" id="WebViewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">      
<script>
    var viewport = document.querySelector("meta[name=viewport]");
    // Set the viewPort according to the device pixel
    if (window.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, the maximum - scale = 0.5, the minimum - scale = 0.5, user - scalable = no');
    }
    if (window.devicePixelRatio == 3) {
        viewport.setAttribute('content'.'width = device - width, initial - scale = 03333333333333333, maximum - scale = 0.3333333333333333, the minimum - scale = 03333333333333333, user-scalable=no');
    }
    var docEl = document.documentElement;
    var fontsize = 32* (docEl.clientWidth / 750) + 'px';
    docEl.style.fontSize = fontsize;
</script>
Copy the code
  • Advantages: convenient, directly write 1px can be
  • Disadvantages: Not applicable to the old project, the scope of influence is relatively large

What are the methods of CSS performance optimization?

  1. Merging CSS files, if the page loads 10 CSS files at 1K each, it is also slower than loading only one CSS file at 100K.
  2. Reduce CSS nesting, preferably not more than three layers.
  3. Do not nest in front of ID selectors; ids are unique and have high permissions; nesting is a waste of performance.
  4. Create a common style class that extracts the same style and uses it as a common class.
  5. Reduce the use of wildcard * or selectors like [hidden=”true”] and look for all… Will it work?
  6. Using CSS inheritance, if the parent node is defined, the child node does not need to be defined.
  7. Split out the common CSS file. For larger projects, you can extract most of the common structural styles of the page into a single CSS file, which will be cached after a single download. Of course, this will increase the number of requests.
  8. Instead of using CSS expressions, expressions just make your code look cool, but they can be more wasteful of performance than you might think.
  9. If you use CSS REST less, you might think that restyling is the norm, but there are a lot of things that are unnecessary and unfriendly. Normolize.css is a good choice if you’re interested.
  10. CssSprite, synthesize all icon images, display icon images in the way of width and height plus background-position, which is very practical and reduces HTTP requests.
  11. After that, CSS compression (YUI Compressor, an online compression tool) is optimized for file size
  12. GZIP compression, a popular file compression algorithm, further reduces network transmission load and improves load performance
  13. Avoid the use of@import, used in external CSS files@importCan cause the page to add an additional delay when loading.
  14. Avoid excessive rearrangement (backflow): The backflow of the browser consumes a large amount of computing resources

Conditions that cause reflow to occur:

  1. Resize the window
  2. Change the size of the text
  3. Add delete style sheets
  4. Change the content of the input box input content will also
  5. Activation of pseudo-classes
  6. Manipulating class attributes
  7. Scripts manipulate DOM JS to change CSS classes
  8. Calculate offsetWidth and offsetHeight
  9. Setting the style property
  10. Change the inner and outer margins of elements

Common reflux elements

  1. Related to the size of the width, height, padding, margins, border width, border, min – height
  2. About the display layout, the top position, float, left, right, bottom
  3. Font size,text-align,font-weight,font-family,line-height,white-space,vertical-align
  4. Hide related overflow,overflow-x,overflow-y

Recommendations for optimizing reflux

  1. Instead of styling the DOM one by one, pre-define the class and then modify the DOM classname
  2. Do not modify dom with a wide range of influence
  3. Use absolute positioning for animation elements
  4. Do not make a table layout, because a small change will cause the entire table to be rearranged
  5. Avoid setting a lot of style attributes. Changing the node style by setting the style attribute will trigger reflow every time, so use the class attribute instead
  6. If the CSS has a calculated expression, it is recalculated each time, triggering a reflow

Transition and animation

  1. transitionNeed to trigger, such as click event, mouse move event, and animation can cooperate@keyframeIt can be executed automatically
  2. transitionTrigger once play once, whileanimationCan be set to modify the number of cycles, animation state and so on.
  3. transitionLook at changes in style properties, and the relationship between property values and time can be a cubic Bezier curve,animationScoped elements themselves rather than style attributes, using the concept of keyframes, allow for more free animation
  4. In terms of performance: the browser has a main thread and a layout thread. The main thread is mainly responsible for JS running, page layout, bitmap generation and so on, and then passes the generated bitmap to the layout thread. The layout thread will draw the bitmap to the page through GPU, and also request the bitmap to the main thread. In the use ofanimationIn the process, we may changewidth.heightChanging the properties of the document flow can cause page backflow and redrawing, which can affect performance. whiletransitionWill combinetransformTo rotate and scale, creating a new layer without causing redraw and reflow.

What are the meanings and usages of calc, support and media?

The @Supprot function is mainly used to check whether the browser supports a CSS attribute. In essence, it is a conditional judgment. If it supports one attribute, apply one style, otherwise provide another style.

@supports (display: grid) {
  div {
    display: grid; }}@supports not (display: grid) {
  div {
    float: right; }}Copy the code

@Supports is accessible in JS through the CSS object interface model CSSSupportsRule.

Calc () is used to dynamically calculate the length value, supporting the conventional four operations /

@media, for media queries to apply different styles.

Advantages and disadvantages of image Base64 encoding

Advantages:

  1. Reduce HTTP requests for an image

Disadvantages:

  1. According to the principle of Base64 encoding, the encoded file size will be 1/3 larger than the source file, if the large image is encoded tohtml/css, which increases the file size, affects the file loading speed, and increases the time for the browser to parse HTML and CSS
  2. Basr64 does not cache images directly
  3. Browsers prior to IE8 do not support it

Layout ViewPort, Visual ViewPort and Ideal ViewPort?

There are three viewports to understand on mobile:

  1. Layout viewport (layout viewport), when displaying the web page on the mobile terminal, due to the small screen size of the mobile terminal, if the web page is laid out using the screen size of the mobile terminal, the whole page will be displayed incorrectly. So mobile browsers provide onelayout viewportThe layout viewport concept, using this viewport to display the page, generallylayout viewportThe size of the page is 980px, so the layout of the page doesn’t change much, and we can view the page by dragging and zooming
  2. Visual port (visual viewport), visual viewport refers to the viewport size of the area we can see, generally the resolution of the screen. The relationship between visual viewport and layout viewport: visual viewport is like a window, and layout viewport is the scenery outside the window.
  3. Ideal viewport (ideal viewport), ideal viewport due tolayout viewportGeneral thanvisual viewportLarge, so you have to drag the page to see the entire page. Hence the concept of the ideal viewport,ideal viewportUsers can see the entire page with different zooming and scrolling bars, and the size of content displayed on the page is the same at different resolutions.ideal viewportIt’s just by modifying itlayout viewportLet the size of the device be large equal to the width of the device, which can be understood as device-independent pixels. So a page designed for an ideal viewport should look the same at different resolutions.

The Settings are as follows:

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

Overflow: How to handle the problem that scrolling cannot be smooth?

{
  -webkit-overflow-scrolling:touch; // Enable hardware acceleration}Copy the code

How does the browser determine whether webP images are supported

  1. Width and height judgment method. Create an image object, set its SRC property to a WebP image, and then get the width and height of the image in the onLoad event, as shown in figure 2

If it can be obtained, the browser supports WebP images. If the onError function cannot be retrieved or raised, the browser does not support WebP grid images.

  1. Canvas judgment method. We can dynamically create a Canvas object, set it to WebP format via the Canvas toDataURL, and decide

Whether the returned value contains the image/webp field. If the value contains the image/ webP field, webP is supported; otherwise, webP is not supported.

What is a replacement element

An element that can be replaced by changing the value of an attribute is called a “replacement element.” Thus, , ,

In addition to the property that content is replaceable, replacement elements have the following properties.

  1. The appearance of the content is not affected by CSS on the page. In technical terms, styles are rendered outside the scope of CSS. How do I change the appearance requirements of the replacement element itself

Like the appearance attribute, or some style interface exposed by the browser itself,

  1. It has its own size. On the Web, the default size (excluding borders) for many replacement elements without an explicit size is 300 pixels by 150 images

Elements, such as

  1. It has its own set of presentation rules for many CSS properties. Typical is the vertical-align attribute, ve for replacement and non-replacement elements

The value of the rtical-align attribute is interpreted differently. For example, the default baseline of vertical-align is defined as the lower edge of the character X, while the baseline of the replacement element is defined as the lower edge of the element.

  1. All replacement elements are inline horizontal elements, that is, replacement elements and replacement elements, replacement elements and text can be displayed on a single line. However, replace elements by default

The display values are inline and inline-block.

Will background-image of hidden elements load?

  1. Background image of element:

    1. Element Settingsdisplay:none, will request an image,
    2. Parent element Settingsdisplay:noneWill not request images
    3. Styles are not used by elements and are not requested
    4. :hoverStyle, when triggered request
  2. Img tag image: Images are requested in any case

Img/background

  1. From the perspective of parsing mechanism:
    1. According to the browser’s parsing mechanism, HTML tags are parsed first.
    2. If you just show an image, for examplebannerAdvertising image, can be usedbackground, the unimportant items are automatically lined to the back to avoid occupying bandwidth and causing data congestion
    3. When images are large and not lazy-loaded, background is a better choice
    4. The nice thing about the IMG tag is that it closes itself and avoids empty notes
  2. From SEO:
    1. Img is a self-closing label and cannot be added with text. It can be setaltProperties.
    2. The advantages are: screen reader friendly; Disadvantages: need to set the display interval
  3. From the perspective of semantics:
    1. Img is a semantic tag

Implement a width and height adaptive square

/*1. The first way is to use VW to implement */
.square {
  width: 10%;
  height: 10vw;
  background: tomato;
}

/*2. The second method uses the fact that the margin/padding percentage of the element is relative to the parent element width to implement */
.square {
  width: 20%; /* 20% of the width of the parent element */
  height: 0;
  padding-top: 20%; /* 20% of the width of the parent element */
  background: orange;
}

/*3. The third way is to use the child element's margin-top value to implement */
.square {
  width: 30%;
  overflow: hidden;
  background: yellow;
}

.square::after {
  content: ' ';
  display: block;
  margin-top: 100%;
}
Copy the code

What is the calculation baseline when different properties in the CSS are set to %?

Formula: The CSS attribute value of the current element = base * the percentage

  • When the position of the element is relative and absolute, the top and bottom, left and right benchmarks are the height and width of the block, respectively
  • When position is fixed, top and bottom, left and right benchmarks are the height and width of the initial block (i.e. viewport) respectively. For more complex mobile devices, the benchmarks are the height and width of the Layout Viewport
  • When the height and width of an element are set to percentages, the base is the height and width of the containing block, respectively
  • *When margin and padding are set to percentages, the base is the width containing the block (error-prone)
  • The border-width of the element does not support percentages
  • The text-indent of the element, based on the width of the containing block
  • Border-radius of the element, based on its height and width, respectively
  • The background-size of the element is its height and width, respectively
  • The translateX and translateY of the element are their height and width respectively
  • The element’s line-height is based on its own font size
  • The font size of the element, based on the parent element font

Refer to the link

  • CSS style priority
  • Enable CSS3 hardware acceleration
  • CSS performance optimization
  • CSS is often tested on interview questions