Summary of front-end CSS classic interview questions

Summary of front-end CSS classic interview questions

2.1 介绍一 下 CSS 的盒子模型?

有两种, IE 盒子模型、W3C 盒子模型;
盒模型: 内容(content)、填充(padding)、边界(margin)、 边框(border);
区 别: IE 的 content 部分把 border 和 padding 计算了进去;

2.2 css 选择器优先级?

!important > 行内样式(比重1000)> ID 选择器(比重100) > 类选择器(比重10) > 标签(比重1) > 通配符 > 继承 > 浏览器默认属性

2.3 垂直居中几种方式?

Single line text: line-height = height
Image: vertical-align: middle;
absolute Positioning: top: 50%;left: 50%;transform: translate(-50%, -50%);
flex: display:flex;margin: auto

2.4 Briefly explain the difference and usage between CSS link and @import?

link is an XHTML tag, in addition to loading CSS, it can also define other things such as RSS; @import belongs to the category of CSS and can only load CSS.
When link refers to CSS, it is loaded at the same time when the page is loaded; @import needs to be loaded after the page is fully loaded.
link is an XHTML tag and has no compatibility issues; @import was proposed in CSS2.1, and browsers of lower versions do not support it.
link supports using Javascript to control DOM to change styles; @import does not.

2.5 What is the difference between the transparency effects of rgba and opacity?

opacity will inherit the opacity attribute of the parent element, and the descendant element of the element set by RGBA will not inherit the opacity attribute.

2.6 What is the difference between display:none and visibility:hidden?

display:none hides the corresponding element, no space is allocated to it in the document layout, and the elements on each side of it will be closed, as if it never existed.
visibility:hidden hides the corresponding element, but retains the original space in the document layout.

2.7 The value of position, relative and absolute are relative to whom are they positioned?

Relative: relative positioning, relative to its own position in the normal document flow.
absolute: Generate absolute positioning, relative to the parent element whose positioning is not static at the nearest level.
fixed: (old version of IE does not support) generate absolute positioning, relative to the browser window or frame for positioning.
static: The default value, no positioning, the element appears in the normal document flow.
sticky: Generate sticky positioned elements, the position of the container is calculated according to the normal document flow.

2.8 Draw a straight line of 0.5px?

The test is the transform of css3

height: 1px;
transform: scale(0.5);

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

  • @support is mainly used to detect whether the browser supports a certain attribute of CSS. In fact, it is a conditional judgment. If it supports a certain attribute, you can write a set of styles. If it does not support a certain attribute, you can also provide another set of styles. as a substitute.
  • The calc() function is used to dynamically calculate the length value. The calc() function supports "+", "-", "*", "/" operations;
  • @media query, you can define different styles for different media types.

2.10 What do 1rem, 1em, 1vh, and 1px represent?

  • rem
    rem is all lengths relative to the root element element. The usual practice is to set a font size for html elements, and then the length unit of other elements is rem.
  • The em of the font size of the em
    sub-element is relative to the font size of the parent element.
    The width/height/padding/margin of the element is relative to the font-size of the element if em is used
  • The full names of vw/vh
    are Viewport Width and Viewport Height. The width and height of the window are equivalent to 1% of the screen width and height. However, the % unit is more appropriate when dealing with width, and the vh unit is better when dealing with height.
  • px
    px pixel (Pixel). Relative length unit. Pixel px is relative to the screen resolution of the monitor.
    The resolution of a general computer is {1920 1024} and other different resolutions
    1920
    1024. The former has a screen width of 1920 pixels in total, while the latter has a height of 1024 pixels.

2.11 Draw a triangle?

This is a simple css test. While using the component library, don’t forget the native css

.a {
    width: 0;
    height: 0;
    border-width: 100px;
    border-style: solid;
    border-color: transparent #0099CC transparent transparent;
    transform: rotate(90deg); /*顺时针旋转90°*/
}
<div class="a"></div>

2.12 Talk about your understanding of CSS modularity

CSS development

When we wrote css, we actually went through the following stages:

  • Handwritten native CSS
  • Using Preprocessor Sass/Less
  • Using post-processor PostCSS
  • Use css modules
  • use css in js

Handwritten native CSS

When we first learned to write pages, everyone learned how to write css, in the following situations:

  • Inline styles, that is, directly write css codes in the style attribute in html.
  • Embedded style, that is, write class in the style tag in html h, and provide it to the current page.
  • Import styles, that is, use the @import method in inline styles to import other styles and provide them for use on the current page.
  • External style, that is, use the link tag in html to load the style and provide it to the current page.

We are constantly exploring, and gradually formed the writing habit of writing embedded styles and external styles .

After reading this, everyone must have doubts, why is it not recommended to use inline styles?

Disadvantages of using inline styles

  • Styles cannot be reused.
  • The style weight is too high, and the style is not well covered.
  • The presentation layer is not separated from the structural layer.
  • Cannot be cached, affecting loading efficiency.

Then let's continue to analyze, why is it not recommended to use import styles?

After testing, using @import in css will have the following two situations:

1. Under IE6-8, the style sheet pointed to by the @import statement will not be loaded concurrently with other resources on the page, but will start downloading after all resources on the page are loaded.

2. If you @import other css in the link tag, the page will wait until all resources are loaded before starting to parse the @import css in the link tag.

Disadvantages of using imported styles

  • Import styles can only be placed in the first line of the style tag, other lines will be invalid.
  • The style sheet declared by @import cannot make full use of the browser's behavior of concurrently requesting resources, and its loading behavior is often delayed or suspended by other resource loading.
  • Page styles may flicker due to lazy loading of @import stylesheets.

Using Preprocessor Sass/Less

With the continuous development of time, we gradually found that writing native css is actually not friendly, for example: native css does not support variables, does not support nesting, does not support parent selectors, etc., these various problems have given rise to preprocessor like sass/less.

The preprocessor mainly strengthens the syntax of css and makes up for the problems mentioned above, but in essence, the packaged result is the same as the original css, but it is friendly to developers and smoother to write.

Post ProcessorPostCSS

With the continuous development of front-end engineering, more and more tools have been developed by front-end leaders. The vision is to hand over all repetitive work to machines, and postcss has emerged in the css field.

postcss can be called babel in the css world. Its implementation principle is to analyze our css code through ast, and then process the analysis results, thus deriving many usage scenarios for processing css.

Common postcss usage scenarios are:

  • Cooperate with stylelint to verify css syntax
  • Automatically increase the browser prefix autoprefixer
  • Syntax for compiling css next

CSS modularity grows rapidly

With the popularization and use of modular-based frameworks such as react and vue, we have fewer and fewer opportunities to write native css. We often split the page into many small components, and then assemble the multiple small components into the final rendered page like building blocks.

But we know that css matches elements based on class names. If two components use the same class name, the latter will overwrite the former’s style. It seems that resolving style naming conflicts is a big problem.

In order to solve this problem, the concept of CSS modularization was born.

CSS Modular Definition

  • Are you struggling with class naming?
  • Do you worry about using the same class name as someone else?
  • Are you annoyed by unclear hierarchy?
  • Are you upset that code is hard to reuse?
  • Are you intimidated by the size of common.css?

If you encounter the above problems, it is necessary to use css modularization.

Implementing CSS Modularity

BEM naming convention

BEM means block (block), element (element), modifier (modifier). It is a front-end naming methodology proposed by the Yandex team. This clever naming method makes your css classes more transparent and meaningful to other developers.

The naming convention of BEM is as follows:

/* 块即是通常所说的 Web 应用开发中的组件或模块。每个块在逻辑上和功能上都是相互独立的。 */
.block {
}

/* 元素是块中的组成部分。元素不能离开块来使用。BEM 不推荐在元素中嵌套其他元素。 */
.block__element {
}

/* 修饰符用来定义块或元素的外观和行为。同样的块在应用不同的修饰符之后,会有不同的外观 */
.block--modifier {
}

The naming method of bem can make our css code hierarchy clear, and the problem of naming conflicts can also be solved through strict naming, but it cannot be completely avoided. After all, it is only a naming constraint, and it can still run if it is not written according to the specification.

CSS Modules

CSS Modules means that we import our css code like import js. Each class name in the code is an attribute of the imported object. In this way, the referenced css style can be clearly specified when using it.

And CSS Modules will automatically convert the class name into a hash value when packaging, completely eliminating the problem of css class name conflicts.

The usage is as follows:

1. Define the css file.

.className {
  color: green;
}
/* 编写全局样式 */
:global(.className) {
  color: red;
}

/* 样式复用 */
.otherClassName {
  composes: className;
  color: yellow;
}

.otherClassName {
  composes: className from "./style.css";
}

2. Import the css file in the js module.

import styles from "./style.css";

element.innerHTML = '<div class="' + styles.className + '">';

3. Configure css-loader packaging.

CSS Modules cannot be used directly, but need to be packaged. Generally, the configuration of css modules can be completed by configuring the modules attribute in css-loader.

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use:{
          loader: 'css-loader',
          options: {
            modules: {
              // 自定义 hash 名称
              localIdentName: '[path][name]__[local]--[hash:base64:5]',
            }
          }
       }
    ]
  }
};

4. The final packaged css class name is generated from a long string of hash values.

._2DHwuiHWMnKTOYG45T0x34 {
  color: red;
}

._10B-buq6_BEOTOl9urIjf8 {
  background-color: blue;
}

CSS In JS

CSS in JS means to use the js language to write css, no separate css files are needed at all, all the css codes are placed inside the component to realize the modularization of css.

CSS in JS is actually a kind of writing idea. At present, more than 40 kinds of solutions have been realized, and the most famous one is styled-components.

The usage is as follows:

import React from "react";
import styled from "styled-components";

// 创建一个带样式的 h1 标签
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// 创建一个带样式的 section 标签
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

// 通过属性动态定义样式
const Button = styled.button`
  background: ${props => (props.primary ? "palevioletred" : "white")};
  color: ${props => (props.primary ? "white" : "palevioletred")};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

// 样式复用
const TomatoButton = styled(Button)`
  color: tomato;
  border-color: tomato;
`;

<Wrapper>
  <Title>Hello World, this is my first styled component!</Title>
  <Button primary>Primary</Button>
</Wrapper>;

可以看到,我们直接在 js 中编写 css,案例中在定义源生 html 时就创建好了样式,在使用的时候就可以渲染出带样式的组件了。

除此之外,还有其他比较出名的库:

  • emotion
  • radium
  • glamorous

总结

最后放一张总结好的图。

img

2.13 说说对 CSS 预编语言的理解,以及它们之间的区别

一、是什么

Css 作为一门标记性语言,语法相对简单,对使用者的要求较低,但同时也带来一些问题

需要书写大量看似没有逻辑的代码,不方便维护及扩展,不利于复用,尤其对于非前端开发工程师来讲,往往会因为缺少 Css 编写经验而很难写出组织良好且易于维护的 Css 代码

Css预处理器便是针对上述问题的解决方案

预处理语言

扩充了 Css 语言,增加了诸如变量、混合(mixin)、函数等功能,让 Css 更易维护、方便

本质上,预处理是Css的超集

包含一套自定义的语法及一个解析器,根据这些语法定义自己的样式规则,这些规则最终会通过解析器,编译生成对应的 Css 文件

二、有哪些

Css预编译语言在前端里面有三大优秀的预编处理器,分别是:

  • sass
  • less
  • stylus

sass

2007 年诞生,最早也是最成熟的 Css 预处理器,拥有 Ruby 社区的支持和 Compass 这一最强大的 Css 框架,目前受 LESS 影响,已经进化到了全面兼容 CssScss

文件后缀名为.sassscss,可以严格按照 sass 的缩进方式省去大括号和分号

less

2009年出现,受SASS的影响较大,但又使用 Css 的语法,让大部分开发者和设计师更容易上手,在 Ruby 社区之外支持者远超过 SASS

Its disadvantage is that the programmable function is not enough in SASS comparison , but the advantage is simplicity and compatibility Css, which in turn affects SASS the evolution of Scssthe era

stylus

Stylus It is a Csspreprocessing framework, produced in 2010, from Node.js the community, mainly used for preprocessing support for NodeprojectsCss

So Stylusis a new kind of language that can create robust, dynamic, expressive Css. is younger and essentially does something SASS/LESSsimilar to

Three, the difference

Although various preprocessors are powerful, the most commonly used features are the following:

  • variables
  • scope
  • Code mixins (mixins)
  • nested (nested rules)
  • Code Modularization (Modules)

Therefore, the differences in these aspects are expanded below

basic use

less and scss

.box {
  display: block;
}

sass

.box
  display: block

stylus

.box
  display: block
nesting

The nesting syntax of the three is consistent, even the tag & that refers to the parent selector is the same

The only difference is that Sass and Stylus can be written without curly braces

less

.a {
  &.b {
    color: red;
  }
}
variable

Variables undoubtedly add an effective reuse method to Css, reducing the unavoidable repetition of "hard coding" in Css

lessThe declared variable must @start with, followed by the variable name and variable value, and the variable name and variable value need to be :separated by a colon

@red: #c00;

strong {
  color: @red;
}

sassThe declared variable is lessvery similar to the variable name, except that the variable name starts $with

$red: #c00;

strong {
  color: $red;
}
stylus`声明的变量没有任何的限定,可以使用`$`开头,结尾的分号`;`可有可无,但变量与变量值之间需要使用`=

stylusWe do not recommend @declaring variables at the beginning of the symbol

red = #c00

strong
  color: red
scope

CssThe precompiler assigns scope to variables, that is, there is a lifetime. Just js like, it will first look up variables from the local scope, and then look up the upper scope in turn

sassThere are no global variables in

$color: black;
.scoped {
  $bg: blue;
  $color: white;
  color: $color;
  background-color:$bg;
}
.unscoped {
  color:$color;
} 

after compilation

.scoped {
  color:white;/*是白色*/
  background-color:blue;
}
.unscoped {
  color:white;/*白色(无全局变量概念)*/
} 

Therefore, sassit is best not to define the same variable name in

lessstylusThe scope of and is javascriptvery similar, firstly, it will search for locally defined variables, if not found, it will search down level by level like bubbling until the root

@color: black;
.scoped {
  @bg: blue;
  @color: white;
  color: @color;
  background-color:@bg;
}
.unscoped {
  color:@color;
} 

After compilation:

.scoped {
  color:white;/*白色(调用了局部变量)*/
  background-color:blue;
}
.unscoped {
  color:black;/*黑色(调用了全局变量)*/
} 
contamination

Mixin should be said to be one of the most essential functions of the preprocessor. To put it simply, Mixinsa part of the style can be extracted as a separately defined module, which can be reused by many selectors

MixinsVariables or default parameters can be defined in

In less, mixed usage refers to ClassAintroducing a defined one into another already defined one Class, and can also be used to pass parameters, parameter variables are @declarations

.alert {
  font-weight: 700;
}

.highlight(@color: red) {
  font-size: 1.2em;
  color: @color;
}

.heads-up {
  .alert;
  .highlight(red);
}

after compilation

.alert {
  font-weight: 700;
}
.heads-up {
  font-weight: 700;
  font-size: 1.2em;
  color: red;
}

SassmixinsIt needs to be used when declaring @mixinn, followed by mixinthe name, and parameters can also be set. The parameter name is in $the form of variable declaration

@mixin large-text {
  font: {
    family: Arial;
    size: 20px;
    weight: bold;
  }
  color: #ff0000;
}

.page-title {
  @include large-text;
  padding: 4px;
  margin-top: 10px;
}

stylusThe mix in Cssis slightly different from the mix of the previous two preprocessor languages. He can directly declare the Mixinsname without using any symbols, and then use the equal sign (=) to connect the defined parameters and default values.

error(borderWidth= 2px) {
  border: borderWidth solid #F00;
  color: #F00;
}
.generic-error {
  padding: 20px;
  margin: 4px;
  error(); /* 调用error mixins */
}
.login-error {
  left: 12px;
  position: absolute;
  top: 20px;
  error(5px); /* 调用error mixins,并将参数$borderWidth的值指定为5px */
} 
code modularization

Modularization is the Cssdivision of code into modules

scss, less, and stylusthe usage methods of the three are as follows

@import './common';
@import './github-markdown';
@import './mixin';
@import './variables';

2.14 How to implement a square with adaptive width and height using only CSS?

We can more or less see the application scenarios of css squares on websites such as e-commerce and personal blogs, and adaptive square layouts must be mastered.

square

It's very simple, just set the width and height of the box to 200px

<div class="box">小明写的</div>

.box {
    width: 200px;
    height: 200px;
    background: pink;
}

adaptive square

bronze

When it comes to self-adaptation, you must think of relative units such as rem and vw . Let's use these units to realize it.

rem
<div class="rem">rem</div>

body {
    font-size: 16px;
}

.rem {
    width: 10rem;
    height: 10rem;
    background: pink;
}

@media only screen and (max-width: 1200px) {
    body {
        font-size: 12px;
    }
}

img

When the screen width is greater than 1200px, the font is 16px, and the size of the rem box is 160px * 160px;

When the screen width is less than 1200px, the font is 12px, and the size of the rem box is 120px * 120px;

The value of rem will be dynamically calculated when the screen width changes in the actual application scenario, which is only used for case understanding.

advantage

In a project adapted to rem, you can directly use rem to set the width and height of the box, that is, an adaptive square

shortcoming

In a project where rem is not set, it is a bit overkill to achieve adaptive square alone

vw

<div class="vw">vw</div>

.vw {
    width: 10vw;
    height: 10vw;
    background: yellow;
}

img

It can be seen that the square adapts to the change of the screen width, which is the effect we want

advantage

vw is the built-in viewport unit and can be used directly.

shortcoming

In actual business scenarios, it is relatively troublesome to convert the size of the design draft into vw

gold

Using percentage + padding , here is a very detailed knowledge point; when the value of padding and margin is a percentage, the value of the percentage is based on the width of the parent element .

<div class="padding"></div>

.padding {
    width: 20%;
    padding-top: 20%;
    /* padding-top或padding-bottom都可以 */
    background: #696969;
}

We set the width of the box to 20%, and the vertical axis of the padding used to expand the height of the box, thus obtaining an adaptive square.

img

Careful friends will find that it is an adaptive square now, but the height is fully occupied and there is no place to put the content. Yes, it is only a square at present; in actual business scenarios, the interior is either pictures or other content, and more than a square is needed.

Solution: Nest another layer of content boxes, the outer square box is relative positioning, and the inner content box is absolute positioning; the width and height of the inner box are based on the outer square box, the code is as follows

<div class="box-wrap">
    <div class="box-content">我是内容区域</div>
</div>

.box-wrap {
    position: relative;
    width: 20%;
    padding-top: 20%;
}

.box-content {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 1;
    background: burlywood;
}

The .box-content class is a content box, and we can restore the design draft as we like in the content box.

If the square area only needs to display pictures, the same reason is as follows

<div class="box-wrap">
    <img src="./img/A.webp" alt="">
</div>

.box-wrap {
    position: relative;
    width: 20%;
    padding-top: 20%;
}

.box-wrap > img {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 1;
    object-fit: cover;
}

img

Here we have implemented an adaptive square image.

advantage

No other configuration is required, flexible settings and strong scalability.

shortcoming

An additional layer of content boxes needs to be nested (personal opinion)

diamond

As the name suggests, it's pretty ugly; it's the css attribute aspect-ratio

aspect-ratio MDN documentation

aspect-ratio,简言之就是宽高比。多说无益,上代码

<div class="box-square">我是内容</div>

.box-square {
    aspect-ratio: 1 / 1;
    /* aspect-ratio: 1; 可简写 */
    width: 20%;
    background: chocolate;
}

img

预览

一个属性,自适应正方形就OK啦;属性再好,也得看兼容性和浏览器支持。

img

优点

属性通俗易懂,无需其他配置,无需嵌套内容盒。

缺点

唯一缺点就是兼容性了,2023年了该支持的基本都支持上了,此事古难全!

活学活用

至此,知识点应该都掌握了吧;让我们来实现一个真实的业务需求,如图

img

实现这个布局,假设总宽1000px,商品卡片左右间距12px,布局要求自适应+响应式。

百分比+padding实现

<main>
    <div class="shop">
        <div class="shop-img"><img src="./img/A.webp" alt=""></div>
        <div class="shop-title">这是小黎测试的文字区域,实际运用一下百分比+padding实现自适应方形布局。</div>
    </div>
    <div class="shop">
        <div class="shop-img"><img src="./img/A.webp" alt=""></div>
        <div class="shop-title">这是小黎测试的文字区域,实际运用一下百分比+padding实现自适应方形布局。</div>
    </div>
   <div class="shop">
        <div class="shop-img"><img src="./img/A.webp" alt=""></div>
        <div class="shop-title">这是小黎测试的文字区域,实际运用一下百分比+padding实现自适应方形布局。</div>
    </div>
    <div class="shop">
        <div class="shop-img"><img src="./img/A.webp" alt=""></div>
        <div class="shop-title">这是小黎测试的文字区域,实际运用一下百分比+padding实现自适应方形布局。</div>
    </div>
</main>
main {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;

    .shop {
        width: calc(25% - 9px);
        box-shadow: 0 0 8px #0002;
        border-radius: 4px;
       overflow: hidden;

        .shop-img {
            position: relative;
            width: 100%;
           padding-top: 100%;

            > img {
                position: absolute;
                width: 100%;
                height: 100%;
                top: 0;
                left: 0;
                z-index: 1;
                object-fit: cover;
            }
        }

        .shop-title {
            padding: 8px;
            font-size: 14px;
            color: #232323;
        }
    }
}

@media only screen and (max-width: 768px) {
    main {

        .shop {
            width: calc(50% - 6px);
            margin-bottom: 12px;
        }
    }
}

来看看效果

img

aspect-ratio实现

使用aspect-ratio了属性,我们可以少嵌套一个外层方形盒

<main>
    <div class="shop">
        <img src="./img/A.webp" alt="">
        <div class="shop-title">这是小黎测试的文字区域,实际运用aspect-ratio实现自适应方形布局。</div>
    </div>
    <div class="shop">
        <img src="./img/A.webp" alt="">
        <div class="shop-title">这是小黎测试的文字区域,实际运用aspect-ratio实现自适应方形布局。</div>
    </div>
    <div class="shop">
        <img src="./img/A.webp" alt="">
        <div class="shop-title">这是小黎测试的文字区域,实际运用aspect-ratio实现自适应方形布局。</div>
    </div>
    <div class="shop">
        <img src="./img/A.webp" alt="">
        <div class="shop-title">这是小黎测试的文字区域,实际运用aspect-ratio实现自适应方形布局。</div>
    </div>
</main>

样式基本不变,改一下图片相关的部分。

main {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;

   .shop {
        width: calc(25% - 9px);
        box-shadow: 0 0 8px #0002;
        border-radius: 4px;
        overflow: hidden;

        > img {
            width: 100%;
            aspect-ratio: 1;
            object-fit: cover;
        }

        .shop-title {
            padding: 8px;
            font-size: 14px;
            color: #232323;
        }
    }
}

@media only screen and (max-width: 768px) {
    main {
        .shop {
            width: calc(50% - 6px);
            margin-bottom: 12px;
        }
    }
}

来看看效果

img

扩展

在实际业务中,应用到的布局不止正方形,也有长方形、圆形等。

我们再来看个需求——UI规定图片区域宽高比为4:3,给的图片也是4:3。

一般情况我们的方案是:设置好图片宽度,高度自适应就OK了。这样做相对简便,但也会存在一些问题;比如图片宽高比并不是4:3,或多或少,又或者传的图不规整;这样会导致我们的页面布局不可控,所谓失之毫厘谬以千里。

这时候就牵扯到了代码健壮性和可扩展性,作为前端开发个人觉得页面应该有良好的用户体验,而不是调教用户。接下来我分别用百分比+padding、aspect-ratio等方案来实现该业务场景。

借用方形示例,这里我就只贴关键代码

百分比+padding实现

main {
    .shop {
        .shop-img {
            width: 100%;
            padding-top: 75%;
        }
    }
}

aspect-ratio实现

main {
    .shop {
        > img {
            width: 100%;
            aspect-ratio: 4 / 3;
            object-fit: cover;
        }
    }
}

看下效果

img

2.15 怎么理解回流跟重绘?什么场景下会触发?

一、是什么

HTML中,每个元素都可以理解成一个盒子,在浏览器解析过程中,会涉及到回流与重绘:

  • 回流:布局引擎会根据各种样式计算每个盒子在页面上的大小与位置
  • 重绘:当计算好盒模型的位置、大小及其他属性后,浏览器根据每个盒子特性进行绘制

具体的浏览器解析渲染机制如下所示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dfKKrtqV-1683893248605)(null)]

  • 解析HTML,生成DOM树,解析CSS,生成CSSOM树
  • 将DOM树和CSSOM树结合,生成渲染树(Render Tree)
  • Layout(回流):根据生成的渲染树,进行回流(Layout),得到节点的几何信息(位置,大小)
  • Painting(重绘):根据渲染树以及回流得到的几何信息,得到节点的绝对像素
  • Display:将像素发送给GPU,展示在页面上

在页面初始渲染阶段,回流不可避免的触发,可以理解成页面一开始是空白的元素,后面添加了新的元素使页面布局发生改变

当我们对 DOM 的修改引发了 DOM 几何尺寸的变化(比如修改元素的宽、高或隐藏元素等)时,浏览器需要重新计算元素的几何属性,然后再将计算的结果绘制出来

当我们对 DOM 的修改导致了样式的变化(colorbackground-color),却并未影响其几何属性时,浏览器不需重新计算元素的几何属性、直接为该元素绘制新的样式,这里就仅仅触发了重绘

二、如何触发

要想减少回流和重绘的次数,首先要了解回流和重绘是如何触发的

回流触发时机

回流这一阶段主要是计算节点的位置和几何信息,那么当页面布局和几何信息发生变化的时候,就需要回流,如下面情况:

  • 添加或删除可见的DOM元素
  • 元素的位置发生变化
  • 元素的尺寸发生变化(包括外边距、内边框、边框大小、高度和宽度等)
  • 内容发生变化,比如文本变化或图片被另一个不同尺寸的图片所替代
  • 页面一开始渲染的时候(这避免不了)
  • 浏览器的窗口尺寸变化(因为回流是根据视口的大小来计算元素的位置和大小的)

还有一些容易被忽略的操作:获取一些特定属性的值

offsetTop、offsetLeft、 offsetWidth、offsetHeight、scrollTop、scrollLeft、scrollWidth、scrollHeight、clientTop、clientLeft、clientWidth、clientHeight

These attributes have one thing in common, that is, they need to be calculated on the fly. Therefore, in order to obtain these values, the browser will also reflow

In addition to getComputedStyle the method, the principle is the same

redraw trigger timing

Triggering a reflow will definitely trigger a redraw

The page can be understood as a blackboard, and there is a small painted flower on the blackboard. Now we want to move this flower from the left to the right, then we need to determine the specific position on the right, draw the shape (reflow), and then paint its original color (redraw)

In addition, there are some other redrawing behaviors:

  • color modification
  • Text Orientation Modification
  • shadow modification

Browser optimization mechanism

Since each rearrangement will cause additional calculation consumption, most browsers will optimize the rearrangement process by queuing modifications and executing them in batches. The browser will put the modification operation into the queue, and the queue will not be emptied until a period of time or the operation reaches a threshold

When you get the operation of layout information, the queue will be forced to refresh, including the methods mentioned above offsetTopwill return the latest data

So the browser has to clear the queue and trigger a reflow repaint to return the correct value

3. How to reduce

We have learned how to trigger reflow and redraw the scene, and the experience of avoiding reflow is given below:

  • If you want to set the style of the element, by changing the class name of the element class(as far as possible in the innermost layer of the DOM tree)
  • Avoid setting multiple inline styles
  • Applies the element's animation, using the value or value positionof the attribute (as mentioned in the previous example)fixedabsolute
  • Avoid using tablethe layout, tablethe size and content of each element in the change will cause the entire tablerecalculation
  • For those complex animations, set them position: fixed/absoluteto make the element out of the document flow as much as possible, so as to reduce the impact on other elements
  • Using css3 hardware acceleration, you can make transform, opacity, and filtersthese animations not cause reflow redrawing
  • Avoid CSS JavaScriptexpressions

When using to JavaScriptdynamically insert multiple nodes, it can be used DocumentFragment. Once created, it can be inserted once. It can avoid multiple rendering performance

But sometimes, we will inevitably reflow or redraw, we can make better use of them

For example, when modifying the layout of an element multiple times, we are likely to do the following

const el = document.getElementById('el')
for(let i=0;i<10;i++) {
    el.style.top  = el.offsetTop  + 10 + "px";
    el.style.left = el.offsetLeft + 10 + "px";
}

Each cycle needs to obtain multiple offsetattributes, which is worse. It can be cached in the form of variables, and then submitted to the browser to issue a recalculation request after the calculation is completed.

// 缓存offsetLeft与offsetTop的值
const el = document.getElementById('el') 
let offLeft = el.offsetLeft, offTop = el.offsetTop

// 在JS层面进行计算
for(let i=0;i<10;i++) {
  offLeft += 10
  offTop  += 10
}

// 一次性将计算结果应用到DOM上
el.style.left = offLeft + "px"
el.style.top = offTop  + "px"

We can also avoid changing styles and use class names to merge styles

const container = document.getElementById('container')
container.style.width = '100px'
container.style.height = '200px'
container.style.border = '10px solid red'
container.style.color = 'red'

Use class names to combine styles

<style>
    .basic_style {
        width: 100px;
        height: 200px;
        border: 10px solid red;
        color: red;
    }
</style>
<script>
    const container = document.getElementById('container')
    container.classList.add('basic_style')
</script>

The former triggers a rendering tree change every time it is operated separately (new browsers will not),

To trigger a rendering tree change, resulting in the corresponding reflow and redraw process

After merging, it means we send all the changes at once

display: noneWe can also remove it from the page by setting element attributes , and then perform subsequent operations, which will not trigger reflow and redrawing. This process is called offline operation

const container = document.getElementById('container')
container.style.width = '100px'
container.style.height = '200px'
container.style.border = '10px solid red'
container.style.color = 'red'

After offline operation

let container = document.getElementById('container')
container.style.display = 'none'
container.style.width = '100px'
container.style.height = '200px'
container.style.border = '10px solid red'
container.style.color = 'red'
...(省略了许多类似的后续操作)
container.style.display = 'block'

2.16 Under what circumstances will the z-index attribute fail?

Usually z-index is used when there are two overlapping labels, and under certain circumstances, one of them appears above or below the other. The higher the z-index value, the higher the layer. The position attribute of the z-index element needs to be relative, absolute or fixed.

The z-index attribute will fail in the following cases:

  • When the position of the parent element is relative, the z-index of the child element becomes invalid. Solution: The position of the parent element is changed to absolute or static;
  • The element does not have a position attribute set to a non-static attribute. Solution: Set the position attribute of the element to one of relative, absolute or fixed;
  • The element also sets float while setting z-index. Solution: remove float and change to display:inline-block;

20230116, a friend added:

  • 在手机端 iOS 13 系统中,-webkit-overflow-scrolling:touch 也会使 z-index 失效,将 touch 换成 unset

具体原因可参考这篇文章: 为什么我的 z-index 又不生效了?

2.17 使用原生js实现以下效果:点击容器内的图标,图标边框变成border:1px solid red,点击空白处重置


const box = document.getElementById('box');

function isIcon(target) {
 return target.className.includes('icon');
}

box.onclick = function(e) {
 e.stopPropagation();
 const target = e.target;
 if (isIcon(target)) {
   target.style.border = '1px solid red';
 }
}

const doc = document;

doc.onclick = function(e) {
 const children = box.children;
 for(let i = 0; i < children.length; i++) {
   if (isIcon(children[i])) {
     children[i].style.border = 'none';
   }
 }
}

2.18 position: fixed 一定是相对于浏览器窗口进行定位吗?

不一定。

position:fixed;的元素会被移出正常文档流,并不为元素预留空间,而是通过指定元素相对于屏幕视口(viewport)的位置来指定元素位置,元素的位置在屏幕滚动时不会改变。fixed 属性会创建新的层叠上下文。

当元素祖先的 transform, perspectivefilter 属性非 none 时,容器由视口改为该祖先。

2.19 css选择器有哪些?优先级分别是什么?哪些属性可以继承?

一、选择器

CSS选择器是CSS规则的第一部分

它是元素和其他部分组合起来告诉浏览器哪个HTML元素应当是被选为应用规则中的CSS属性值的方式

选择器所选择的元素,叫做“选择器的对象”

我们从一个Html结构开始

<div id="box">
	<div class="one">
	    <p class="one_1"></p>
	    <p class="one_1"></p>
	</div>
	<div class="two"></div>
	<div class="two"></div>
	<div class="two"></div>
</div>

关于css属性选择器常用的有:

1- id选择器(#box),选择id为box的元素
2- 类选择器(.one),选择类名为one的所有元素
3- 标签选择器(div),选择标签为div的所有元素
4- 后代选择器(#box div),选择id为box元素内部所有的div元素
5- 子选择器(.one>one_1),选择父元素为.one的所有.one_1的元素
6- 相邻同胞选择器(.one+.two),选择紧接在.one之后的所有.two元素
7- 群组选择器(div,p),选择div、p的所有元素

还有一些使用频率相对没那么多的选择器:

  • 伪类选择器
1:link :选择未被访问的链接
2:visited:选取已被访问的链接
3:active:选择活动链接
4:hover :鼠标指针浮动在上面的元素
5:focus :选择具有焦点的
6:first-child:父元素的首个子元素
  • 伪元素选择器
1:first-letter :用于选取指定选择器的首字母
2:first-line :选取指定选择器的首行
3:before : 选择器在被选元素的内容前面插入内容
4:after : 选择器在被选元素的内容后面插入内容
  • 属性选择器
1[attribute] 选择带有attribute属性的元素
2[attribute=value] 选择所有使用attribute=value的元素
3[attribute~=value] 选择attribute属性包含value的元素
4[attribute|=value]:选择attribute属性以value开头的元素

CSS3中新增的选择器有如下:

  • 层次选择器(p~ul),选择前面有p元素的每个ul元素
  • 伪类选择器
1:first-of-type 父元素的首个元素
2:last-of-type 父元素的最后一个元素
3:only-of-type 父元素的特定类型的唯一子元素
4:only-child 父元素中唯一子元素
5:nth-child(n) 选择父元素中第N个子元素
6:nth-last-of-type(n) 选择父元素中第N个子元素,从后往前
7:last-child 父元素的最后一个元素
8:root 设置HTML文档
9:empty 指定空的元素
10:enabled 选择被禁用元素
11:disabled 选择被禁用元素
12:checked 选择选中的元素
13:not(selector) 选择非 <selector> 元素的所有元素
  • 属性选择器
[attribute*=value]:选择attribute属性值包含value的所有元素
[attribute^=value]:选择attribute属性开头为value的所有元素
[attribute$=value]:选择attribute属性结尾为value的所有元素

二、优先级

相信大家对CSS选择器的优先级都不陌生:

内联 > ID选择器 > 类选择器 > 标签选择器

到具体的计算层⾯,优先级是由 A 、B、C、D 的值来决定的,其中它们的值计算规则如下:

  • A = 1 if inline styles exist, otherwise A = 0
  • The value of B is equal to the number of occurrences of the ID selector
  • The value of C is equal to the total number of occurrences of class selectors and attribute selectors and pseudo-classes
  • The value of D is equal to the total number of occurrences of tag selectors and pseudo-elements

Here is an example:

1#nav-global > ul > li > a.nav-link

Apply the above algorithm to find A B C Dthe value of in turn:

  • A = 0 because there are no inline styles
  • A total of 1 occurrences of the ID selector, B = 1
  • The class selector appears 1 time, the attribute selector appears 0 times, and the pseudo-class selector appears 0 times, so C = (1 + 0 + 0) = 1
  • The label selector appears 3 times, and the pseudo-element appears 0 times, so D = (3 + 0) = 3

The above calculated A, B, C, Dcan be abbreviated as:(0, 1, 1, 3)

After knowing how the priority is calculated, let's take a look at the comparison rules:

  • Compare from left to right, the larger one has higher priority
  • If they are equal, continue to move one bit to the right for comparison
  • If all 4 bits are equal, the latter will overwrite the former

After the above priority calculation rules, we know that inline styles have the highest priority. If external styles need to override inline styles, we need to use!important

3. Inherited properties

In css, inheritance refers to setting some attributes for the parent element, and the descendant elements will automatically have these attributes. Regarding the inheritance attribute, it can be divided into:

  • font family attribute
1font:组合字体
2font-family:规定元素的字体系列
3font-weight:设置字体的粗细
4font-size:设置字体的尺寸
5font-style:定义字体的风格
6font-variant:偏大或偏小的字体
  • Text Series Properties
1text-indent:文本缩进
2text-align:文本水平对齐
3line-height:行高
4word-spacing:增加或减少单词间的空白
5letter-spacing:增加或减少字符间的空白
6text-transform:控制文本大小写
7direction:规定文本的书写方向
8color:文本颜色
  • element visibility
1visibility
  • Table Layout Properties
1caption-side:定位表格标题位置
2border-collapse:合并表格边框
3border-spacing:设置相邻单元格的边框间的距离
4empty-cells:单元格的边框的出现与消失
5table-layout:表格的宽度由什么决定
  • list property
1list-style-type:文字前面的小点点样式
2list-style-position:小点点位置
3list-style:以上的属性可通过这属性集合
  • quote
1quotes:设置嵌套引用的引号类型
  • cursor properties
1cursor:箭头可以变成需要的形状

A few special points in inheritance:

  • The font color of a tag cannot be inherited
  • The size of the h1-h6 label font cannot be inherited

no inherited properties

  • display
  • Text attributes: vertical-align, text-decoration
  • Properties of the box model: width, height, inner and outer margins, borders, etc.
  • Background properties: background image, color, position, etc.
  • Positioning properties: float, clear float, position position, etc.
  • Generate content attributes: content, counter-reset, counter-increment
  • Outline style attributes: outline-style, outline-width, outline-color, outline
  • Page style attributes: size, page-break-before, page-break-after

2.20 How to trigger BFC, and what application scenarios does BFC have?

document flow

Before introducing BFC, we need to introduce the document flow to you.

The document flow we often say is actually divided into three types 定位流: , 浮动流, and 普通流.

Absolute positioning

If the element's attribute positionis absoluteor fixed, it is an absolutely positioned element.

In the absolute positioning layout, the element will be out of the normal flow as a whole, so the absolute positioning element will not affect its sibling elements, and the specific position of the element is determined by the coordinates of the absolute positioning.

It is positioned relative to its containing block, relevant CSS properties: top, bottom, left, right;

For position: absolute, element positioning will be relative to the nearest one of the parent elements relative、fixed、absolute, or relative to body if none;

For position:fixed, it is normally positioned relative to the browser window, but when the attribute of the ancestor of the element is not , it will be positioned relative to the ancestortransformnone .

float

In the floating layout, elements first appear in the position of the normal flow, and then offset to the left or right as much as possible according to the floating direction, the effect is similar to the text wrapping in typography.

normal flow

Ordinary flow actually refers to FC in BFC. FC( Formatting Context), literally translated, is the formatting context, which is a rendering area in the page, with a set of rendering rules, which determine how its sub-elements are laid out, as well as the relationship and function with other elements.

In normal flow, elements are laid out top-to-bottom according to their sequential positions in HTML. In this process, inline elements are arranged horizontally until the line is full and then wrap. Block-level elements are rendered as a whole new line.

Unless otherwise specified, all elements default to normal flow positioning, that is, the position of an element in normal flow is determined by the position of the element in the HTML document.

BFC concept

First look at the definition of BFC on MDN:

The block formatting context ( Block Formatting Context, BFC) is part of the visual CSS rendering of a web page, and is the area where the layout process for block boxes occurs, and where floated elements interact with other elements.

Elements with BFCcharacteristics can be regarded as isolated independent containers, the elements inside the container will not affect the outside elements in layout, and BFChave some characteristics that ordinary containers do not have.

In layman's terms, it can be BFCunderstood as a large closed box. No matter how overwhelming the elements inside the box, it will not affect the outside.

In addition to BFC, there are:

  • IFC(row-level formatting context) - inlineinline
  • GFC(grid layout formatting context) -display: grid
  • FFC(adaptive formatting context) - display: flexordisplay: inline-flex

Note : The same element cannot exist in two at the same time BFC.

BFC trigger mode

MDN has written a lot about the trigger conditions of BFC . To summarize, the common trigger methods are (only one condition needs to be met to trigger the characteristics of BFC):

  • the root element, i.e.<html>
  • Float element: floatvalue is left,right
  • overflowThe value is not visible, that is auto, scroll,hidden
  • displayValues ​​are inline-block, table-cell, table-caption, table, inline-table, flex, inline-flex, grid,inline-grid
  • Absolutely positioned elements: positionvalues ​​are absolute,fixed

Characteristics of BFC

  • BFC is an independent container on the page, and the child elements inside the container will not affect the elements outside.
  • Block-level boxes inside the BFC are arranged vertically one after the other
  • Adjacent block-level elements under the same BFC may have margin collapse, and creating a new BFC can avoid margin collapse
  • The left side of each element's margin box ( margin box) touches the left side of the containing block's border box ( border box) (or vice versa for right-to-left formatting), even with floats
  • The region of the floating box will not overlap with the BFC
  • When calculating the height of BFC, floating elements will also participate in the calculation

application

BFC is an isolated independent container on the page, and the child elements inside the container will not affect the outer elements, and vice versa. We can use this feature of BFC to do many things.

Adaptive two-column layout

The left column is floating (fixed width or variable width is acceptable), and BFC is enabled for the right column.

<div>
    <div class="left">浮动元素,无固定宽度</div>
    <div class="right">自适应</div>
</div>
* {
    margin: 0;
    padding: 0;
}
.left {
    float: left;
    height: 200px;
    margin-right: 10px;
    background-color: red;
}
.right {
    overflow: hidden;
    height: 200px;
    background-color: yellow;
}

Effect:

img

  • Set the left column to float to the left, and collapse its own height so that other block-level elements can occupy the same row as it.
  • The right column is a div block-level element, which uses its own flow characteristics to fill the entire row.
  • Set overflow: hidden in the right column to trigger the BFC feature to isolate itself from the floating elements in the left column and not occupy the entire row.

This is one of the characteristics of the BFC mentioned above: the area of ​​​​the floating box will not overlap with the BFC

Prevent margins from overlapping

Overlapping margins between sibling elements

<div>
    <div class="child1"></div>
    <div class="child2"></div>
</div>
* {
    margin: 0;
    padding: 0;
}
.child1 {
    width: 100px;
    height: 100px;
    margin-bottom: 10px;
    background-color: red;
}
.child2 {
    width: 100px;
    height: 100px;
    margin-top: 20px;
    background-color: green;
}

Effect:

img

Two block-level elements, the red div is 10px from the bottom, and the green div is 20px from the top. Logically, the distance between the two block-level elements should be 30px, but the one with the larger distance is actually taken, that is, 20px.

The upper and lower margins of block-level elements are sometimes merged (or folded) into one outer margin, whose size is the larger one. This behavior is called outer margin collapse (overlapping). Note that this happens when the Between block-level elements under the same BFC

According to the BFC feature, creating a new BFC will not cause margin collapse. For example, if we wrap a layer of containers on the outer layer of their two divs, add attributes overflow: hidden, and trigger BFC, then the two divs do not belong to the same BFC.

<div>
    <div class="parent">
        <div class="child1"></div>
    </div>
    <div class="parent">
        <div class="child2"></div>
    </div>
</div>
.parent {
    overflow: hidden;
}

/* ... */

img

There are other solutions besides triggering BFC for the problem of overlaying the outer margins of sibling elements. For example, if you only use the top or bottom margins uniformly, you will not have the above problems.

Margins of parent and child elements overlap

This condition exists between a parent element and its first or last child element (nested elements).

If there is no border, padding, inline content between the parent element and its first/last child element, and no block formatting context is created, or clear floats separate the margins of the two, then the child element's Margins "overflow" outside of the parent element.

<div id="parent">
  <div id="child"></div>
</div>
* {
    margin: 0;
    padding: 0;
}
#parent {
    width: 200px;
    height: 200px;
    background-color: green;
    margin-top: 20px;
}
#child {
    width: 100px;
    height: 100px;
    background-color: red;
    margin-top: 30px;
}

img

As shown above, the red div is inside the green div, and is set margin-topto 30px, but we found that the top of the red div coincides with the top of the green div, and is not 30px from the top, but overflows to the outside of the parent element for calculation. That is to say, the parent element is only 20px away from the top, but it is affected by the overflow of the child element, and the outer margin overlaps. If the larger value is taken, the distance from the top is 30px.

Solution:

  • Trigger BFC for the parent element (such as adding overflow: hidden)
  • Add border to parent element
  • Add padding to the parent element

This will achieve the desired effect:

img

Clear the float to solve the problem of collapsing the height of the parent element

When the child element in the container is set to float, it breaks away from the document flow, and the total height of the parent element in the container is only the height of the border part.

<div class="parent">
  <div class="child"></div>
</div>
* {
    margin: 0;
    padding: 0;
}
.parent {
    border: 4px solid red;
}
.child {
    float: left;
    width: 200px;
    height: 200px;
    background-color: blue;
}

img

Solution: trigger BFC for the parent element, so that it has BFC characteristics: When calculating the height of BFC, floating elements will also participate in the calculation

.parent {
    overflow: hidden;
    border: 4px solid red;
}

img

We all use overflow: hiddentriggering BFC above, because it is indeed commonly used, but there is more than one way to trigger BFC.

As written above, you can set float: left;, float: right;, display: inline-block;, overflow: auto;, display: flex;, display: table;, positionfor absoluteor fixedetc., all of which can be triggered, but the width of the parent element may not be the same, but the height of the parent element is stretched out.

Of course, the actual application is not to pick one at random, but to choose according to the scene.

2.21 Talk about the understanding of CSS engineering

CSS is engineered to solve the following problems:

  1. Macro design : How to organize CSS code, how to split, how to design module structure?
  2. Coding optimization : how to write better CSS?
  3. Build : What do I do with my CSS so that it packs optimally?
  4. Maintainability : After the code is written, how to minimize its subsequent change cost? How to ensure that any one of the colleagues can easily take over?

The following three directions are popular and universal CSS engineering practices:

  • Preprocessor: Less, Sass, etc.;
  • Important engineering plug-ins: PostCss;
  • Webpack loaders, etc.

Based on these three directions, some typical sub-problems can be derived, here we look at them one by one:

(1) Preprocessor: Why use a preprocessor? What problem does it appear to solve?

The preprocessor is actually the "wheel" of the CSS world. Preprocessors allow us to write a CSS-like language that isn't actually CSS, and then compile it into CSS code:

img

Then why write CSS code that is well written, why do you want to write "CSS-like"? This is the same as using JS to achieve all the functions, but in the end it is the same as writing React's jsx or Vue's template syntax.

With the increasing complexity of front-end business, the following requirements are put forward for CSS in front-end engineering:

  1. Macro design: We hope to optimize the directory structure of CSS files and reuse existing CSS files;
  2. Coding optimization: We hope to be able to write CSS with a clear structure, concise and easy to understand, and need it to have a clear nested hierarchical relationship, rather than an indiscriminate one-to-one writing method; we hope it has variable characteristics, calculation capabilities, and loop capabilities Wait for stronger programmability, so that we can write less useless code;
  3. In terms of maintainability: stronger programmability means better code structure, realizing reuse means simpler directory structure and stronger expansion ability. If these two points can be achieved, it will naturally bring stronger maintainability.

These three points are what traditional CSS cannot do, and it is the problem that the preprocessor solves. Preprocessors generally have the following features:

  • The ability to nest codes to reflect the hierarchical relationship between different css attributes through nesting;
  • Support for defining css variables;
  • Provide calculation functions;
  • Allows to extend and mixin code snippets;
  • Support the use of loop statements;
  • Support modularization of CSS files for reuse.

(2) PostCss: How does PostCss work? In what scenario do we use PostCss?

img

The difference between it and the preprocessor is that the preprocessor processes CSS-like, while PostCss processes CSS itself. Babel can convert high version JS code to low version JS code. PostCss does a similar thing: it can compile advanced CSS syntax that is not yet widely supported by browsers, and can automatically add prefixes to some syntax that requires additional compatibility. What's more, because PostCss has a powerful plug-in mechanism, it supports various extensions, which greatly strengthens the capabilities of CSS.

There are many usage scenarios of PostCss in business:

  • Improve the readability of CSS code: PostCss can actually do a job similar to what a preprocessor can do;
  • When our CSS code needs to adapt to low-version browsers, the PostCss Autoprefixer plug-in can help us automatically increase the browser prefix;
  • Allow us to write future-proof CSS: PostCss can help us compile CSS next code;

(3) Can Webpack handle CSS? How to achieve?

  • Webpack cannot process CSS in the state of streaking . Webpack itself is a modular packaging tool that is oriented to JavaScript and can only process JavaScript code;
  • With the help of loader, Webpack can handle CSS.

How to implement CSS processing with Webpack:

  • There are two key loaders needed to operate CSS in Webpack: css-loader and style-loader
  • Note that answering "what to use" may not be enough sometimes. The interviewer will wonder if you are memorizing the answer, so you also need to know what each loader does:
    • css-loader: import CSS module, compile and process CSS code;
    • style-loader:创建style标签,把 CSS 内容写入标签。

在实际使用中,css-loader 的执行顺序一定要安排在 style-loader 的前面。因为只有完成了编译过程,才可以对 css 代码进行插入;若提前插入了未编译的代码,那么 webpack 是无法理解这坨东西的,它会无情报错。

2.22 为什么有时候⽤translate来改变位置⽽不是使用position进行定位?

translate 是 transform 属性的⼀个值。

改变transform或opacity不会触发浏览器重新布局(reflow)或重绘(repaint),只会触发复合(compositions)。

⽽改变绝对定位会触发重新布局,进⽽触发重绘和复合。

transform使浏览器为元素创建⼀个 GPU 图层,但改变绝对定位会使⽤到 CPU。

因此translate()更⾼效,可以缩短平滑动画的绘制时间。

⽽translate改变位置时,元素依然会占据其原始空间,绝对定位就不会发⽣这种情况。

具体的原理可查看 【前端基础系列】CSS篇-带你搞懂“硬件加速”

2.23 硬件加速的原理是什么?

面试中可能会经常会碰到怎么解决动画卡顿的问题,然后会引导到硬件加速。那么究竟什么是硬件加速,为什么它可以提高咱们的动画效率?我们今天就来一探究竟。

首先,我们先从 CPU 和 GPU 开始了解。

CPU 和 GPU 的区别

CPU 即中央处理器,GPU 即图形处理器。

CPUIt is the brain of the computer, which provides a set of instruction sets, and the programs we write will eventually CPUcontrol the operation of the computer through instructions. It decodes the instruction and executes it through logic circuits. The entire execution process is divided into multiple stages, called the pipeline. The instruction pipeline consists of 指令、译码、执行、取数、写回five fetch steps, which is one instruction cycle. CPUIt will continue to execute instruction cycles to complete various tasks.

GPU, is Graphics ProcessingUnitan abbreviation, is a very important part of a modern graphics card, its status is CPUconsistent with the status on the motherboard, and its main task is to accelerate the graphics processing speed. GPU is the "brain" of the graphics card, which determines the grade and most of the performance of the graphics card, and is also the basis for the difference between 2D graphics cards and 3D graphics cards. 2D display chips mainly rely on the processing power of the CPU when processing 3D images and special effects, which is called "soft acceleration". The 3D display chip concentrates the three-dimensional image and special effect processing functions in the display chip, which is the so-called "hardware acceleration" function.

To explain the difference between the two, you must first understand the similarities between the two: both have buses and external connections, have their own cache systems, and digital and logical operation units.

In a word, both are designed to complete computing tasks.

The difference between the two lies in the structural difference between the on-chip cache system and the digital logic operation unit:

  • CPUAlthough there are multiple cores, the total number does not exceed two digits. Each core has a large enough cache and enough digital and logical operation units, and is assisted by many hardware that accelerates branch judgment or even more complex logic judgment;
  • GPUThe number of cores is far more CPUthan that of many cores (NVIDIA Fermi has 512 cores). The cache size of each core is relatively small, and the digital logic operation unit is also small and simple (it has GPUalways been weaker in floating-point calculations initially CPU).

As a result, it CPUis good at processing computing tasks with complex computing steps and complex data dependencies, such as distributed computing, data compression, artificial intelligence, physical simulation, and many other computing tasks.

GPUDue to historical reasons, it was produced for video games (so far its main driving force is still the growing video game market), a type of operation that often appears in 3D games is to perform the same operation on massive data, such as: for each The same coordinate transformation is performed on the vertices, and the color value is calculated according to the same lighting model for each vertex.

The many-core architecture of the GPU is very suitable for sending the same instruction stream to many cores in parallel and executing them with different input data. It is widely used in the field of general computing, including: numerical analysis, massive data processing (sorting, Map-Reduce, etc.), financial analysis, etc.

In a nutshell, when programmers write programs for CPUs, they tend to utilize complex logic structures to optimize algorithms in order to reduce the running time of computing tasks, ie Latency. ThroughputWhen programmers write programs for the GPU, they take advantage of its ability to process massive amounts of data and cover it up by increasing the total data throughput ( ) Lantency.

At present, the difference between CPUand GPUis gradually narrowing, because GPU has also made great progress in handling irregular tasks and inter-thread communication.

Execution steps for each frame

The refresh rate of a general browser is 60HZ, that is, 60 refreshes per second.

1000ms / 60hz = 16.6, that is, about 16.6msone frame will be rendered every time the browser is passed.

The rendering of each frame by the browser must be completed within 16ms. If this time is exceeded, the rendering of the page will be stuck, which will affect the user experience.

In a brief summary, the browser will perform the following actions sequentially in each frame:

  • JavaScript: JavaScript implements animation effects, DOM element operations, etc.
  • Style(Computed Styles): Determines what CSS rules should be applied to each DOM element.
  • Layout(layout): Calculates the size and position of each DOM element as it will appear on the final screen. Since the element layout of a web page is relative, any change in the position of any element will cause changes in other elements. This process is called reflow.
  • Paint(Drawing): Draws text, colors, images, borders, shadows, etc. of DOM elements on multiple layers.
  • Composite(Rendering layer merging): Merge layers in a reasonable order and display them on the screen.

Reducing or avoiding layoutcan paintmake the page less stuck and the animation effect smoother.

complete rendering process

More specifically, a complete rendering step can be roughly summarized as follows:

  • The rendering process converts HTML content into a human-readable DOM tree structure.
  • The rendering engine converts the CSS style sheet into something the browser can understand styleSheets, and calculates the style of the DOM node.
  • Create a layout tree and calculate layout information for elements.
  • Hierarchize the layout tree and generate a hierarchical tree.
  • Generate a drawlist for each layer and submit it to the compositing thread.
  • The compositing thread divides the layer into tiles and converts the tiles into bitmaps in the rasterizer thread pool.
  • The compositing thread sends the drawing tile command DrawQuad to the browser process.
  • The browser process generates a page according to the DrawQuad message and displays it on the monitor

Normal Layers and Composite Layers

In the introduction above, compositethe concept is mentioned.

It can be simply understood that the layers rendered by the browser generally include two categories: 渲染图层(普通图层)and复合图层

  • Rendering layer: Also known as the default composite layer, it is the common document flow of the page. Although we can use absolute positioning, relative positioning, and floating positioning to break away from the document flow, it still belongs to the default composite layer and shares the same drawing context object ( GraphicsContext).
  • Composite layer, which will allocate resources separately (of course, it will also break away from the normal document flow, so that no matter what changes in this composite layer, it will not affect the reflow redrawing in the default composite layer)

Some special render layers will be promoted to composite layers ( Compositing Layers), and composite layers have a separate one GraphicsLayer, while other render layers that are not composite layers GraphicsLayershare one with their first parent layer.

Each GraphicsLayerhas one GraphicsContext, GraphicsContextwhich is responsible for outputting the bitmap of this layer. The bitmap is stored in the shared memory and uploaded to the GPU as a texture. Finally, the GPU synthesizes multiple bitmaps and then draws them to the screen. At this time , and our page is displayed on the screen.

可以 Chrome源码调试 -> More Tools -> Rendering -> Layer borders中看到,黄色的就是复合图层信息。

硬件加速

硬件加速,直观上说就是依赖 GPU 实现图形绘制加速,软硬件加速的区别主要是图形的绘制究竟是 GPU 来处理还是 CPU,如果是 GPU,就认为是硬件加速绘制,反之,则为软件绘制。

一般一个元素开启硬件加速后会变成复合图层,可以独立于普通文档流中,改动后可以避免整个页面重绘,提升性能。

常用的硬件加速方法有:

  • 最常用的方式:translate3dtranslateZ
  • opacity 属性/过渡动画(需要动画执行的过程中才会创建合成层,动画没有开始或结束后元素还会回到之前的状态)
  • will-change属性(这个知识点比较冷僻),一般配合 opacitytranslate 使用(而且经测试,除了上述可以引发硬件加速的属性外,其它属性并不会变成复合层),作用是提前告诉浏览器要变化,这样浏览器会开始做一些优化工作(这个最好用完后就释放)
  • <video><iframe><canvas><webgl>等元素
  • 其它,譬如以前的 flash 插件

当然,有的时候我们想强制触发硬件渲染,就可以通过上面的属性,比如

1will-change: transform; 

或者

1transform:translate3d(0, 0, 0);

使用硬件加速的注意事项

使用硬件加速并不是十全十美的事情,比如:

  • 内存。如果GPU加载了大量的纹理,那么很容易就会发生内容问题,这一点在移动端浏览器上尤为明显,所以,一定要牢记不要让页面的每个元素都使用硬件加速。
  • 使用GPU渲染会影响字体的抗锯齿效果。这是因为GPU和CPU具有不同的渲染机制。即使最终硬件加速停止了,文本还是会在动画期间显示得很模糊。

所以不要大量使用复合图层,否则由于资源消耗过度,页面可能会变的更加卡顿。

同时,在使用硬件加速时,尽可能的使用z-index,防止浏览器默认给后续的元素创建复合层渲染。

具体的原理是这样的:

webkit CSS3中,如果一个元素添加了硬件加速,并且z-index层级比较低,那么在这个元素的后面其它元素(层级比这个元素高的,或者相同的,并且releativeabsolute属性相同的),会默认变为复合层渲染,如果处理不当会极大的影响性能。

简单点理解,其实可以认为是一个隐式合成的概念:如果a是一个复合图层,而且b在a上面,那么b也会被隐式转为一个复合图层,这点需要特别注意。

2.24 CSS动画和JS实现的动画分别有哪些优缺点?

CSS动画

优点

  • 浏览器可以对动画进行优化
  • 代码相对简单,性能调优方向固定
  • 对于帧速表现不好的低版本浏览器,CSS3可以做到自然降级,而JS则需要撰写额外代码

缺点

  • 运行过程控制较弱,无法附加事件绑定回调函数
  • 代码冗长,想用CSS实现稍微复杂一点动画,最后CSS代码都会变得非常笨重

JS动画

优点

  • 控制能力很强, 可以在动画播放过程中对动画进行控制:开始、暂停、回放、终止、取消都是可以做到的。
  • 动画效果比css3动画丰富,有些动画效果,比如曲线运动,冲击闪烁,视差滚动效果,只有js动画才能完成
  • CSS3有兼容性问题,而JS大多时候没有兼容性问题

缺点

  • 代码的复杂度高于CSS动画
  • JavaScript在浏览器的主线程中运行,而主线程中还有其它需要运行的JavaScript脚本、样式计算、布局、绘制任务等,对其干扰导致线程可能出现阻塞,从而造成丢帧的情况

2.25 前端实现动画有哪些方式?

前端常用的动画实现方式有以下种:

  1. css3的transition 属性
  2. css3的animation 属性
  3. 原生JS动画
  4. 使用canvas绘制动画
  5. SVG动画
  6. Jquery的animate函数
  7. 用gif图片

1. css3的transition

transition属性:

用来设置样式的属性值是如何从一种状态平滑过渡到另外一种状态

语法:

1transition: property duration timing-function delay;

transition是一种简写属性,它可以拆分为四个过渡属性。你可以 transition: 值1,值2,值3,值4 这样写,也可以:transition-property: 值1;transition-duration:值2;transition-timing-function:值2;transition-delay:值4;这样写。

描述
transition-property 规定设置过渡效果的 CSS 属性的名称。
transition-duration 规定完成过渡效果需要多少秒或毫秒。
transition-timing-function 规定速度效果的速度曲线。
transition-delay 定义过渡效果何时开始。

演示代码:

<div></div>

div{
  width:50px;
  height: 50px;
  background-color: pink;
}

div:hover{
  width:200px;
}

效果图:

img

由上图可看出:鼠标移入移出时,width状态的变化是瞬间完成的。

添加transition: 1s;

div{
  width:50px;
  height: 50px;
  background-color: pink;
  transition: 1s;
}
div:hover{
  width:200px;
}

效果图:

img

transition: 1s; 设置了width属性状态变化的过渡时间为1秒。

transition`属性默认为:`transition: all 0 ease 0;
transition:1s;` 等价于 `transition: all 1s ease 0;

2. css3的animation

animation属性:比较类似于 flash 中的逐帧动画。学习过 flash的同学知道,这种逐帧动画是由关键帧组成,很多个关键帧连续的播放就组成了动画在 CSS3 中是由属性keyframes来完成逐帧动画的。

animation属性与transition属性的区别:

  • transition只需指定动画的开始和结束状态,整个动画的过程是由特定的函数控制,你不用管它。
  • animation可以对动画过程中的各个关键帧进行设置

演示代码:

<div></div>

1div{
	width:50px;
	height:50px;
	background-color: pink;
}
div:hover{
	animation: change1 5s;
}
@keyframes change1{
	25%  {width:130px;background-color: red;}
	50%  {width:170px;background-color: blue;}
	75%  {width:210px;background-color: green;}
	100% {width:250px;background-color: yellow;}
}

效果图:

img

3. 原生JS动画

其主要思想是通过setInterval或setTimeout方法的回调函数来持续调用改变某个元素的CSS样式以达到元素样式变化的效果。

javascript 实现动画通常会导致页面频繁性重排重绘,消耗性能,一般应该在桌面端浏览器。在移动端上使用会有明显的卡顿。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style type="text/css">
        #rect {
            width: 200px;
            height: 200px;
            background: #ccc;
        }
    </style>
</head>
<body>
    <div id="rect"></div>
    <script>
        let elem = document.getElementById('rect');
        let left = 0;
        let timer = setInterval(function(){
            if(left<window.innerWidth-200){
                elem.style.marginLeft = left+'px';
                left ++;
            }else {
                clearInterval(timer);
            }
        },16);
    </script>
</body>
</html>

In the above example, the setInterval time interval we set is 16ms. It is generally believed that the smooth animation that the human eye can recognize is 60 frames per second. Here, 16ms is slightly smaller than (1000ms/60) frames, but generally the animation is still smooth.

When optimizing the performance of many mobile-side animations, 16ms is generally used to throttling and processing continuously triggered browser events. For example, throttling touchmove and scroll events. By reducing the trigger frequency of continuous events in this way, the fluency of animation can be greatly improved.

4. Using canvasdraw animation

As a new element of H5, canvas realizes animation with the help of Web API.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    *{
        margin:0;
        padding:0;
    }
    </style>
</head>
<body>
    <canvas id="canvas" width="700" height="550"></canvas>
    <script type="text/javascript">
        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        let left = 0;
        let timer = setInterval(function(){
            ctx.clearRect(0,0,700,550);
            ctx.beginPath();
            ctx.fillStyle = "#ccc";
            ctx.fillRect(left,0,100,100);
            ctx.stroke();
            if(left>700){
                clearInterval(timer);
            }
            left += 1;
        },16);
    </script>
</body>
</html>

Note: Obtain the drawing object of the element through getContext(), constantly clear the canvas through clearRect and use fillStyle to draw new rectangular content at the new position to achieve page animation effects.

The main advantage of Canvas is that it can cope with the slow rendering of multiple animation elements on the page, and completely render and control the execution of animation through javascript. Can be used to implement more complex animations.

5. SVG animation

SVG is an XML-based image format, very similar to how HTML works. It defines different elements for many familiar geometric shapes that can be combined in markup to produce two-dimensional figures.

The same high-definition texture, vector graphics are not afraid to enlarge, small size.

One thing to point out here is that because SVG stores point, line, and surface information, it has nothing to do with resolution and graphic size, but only with the complexity of the image, so the storage space occupied by image files is usually smaller than png.

Advantages of SVG animation:

  • A sharp tool for optimizing SEO and accessibility, because SVG images use XML (Extensible Markup Language [English: Extensible Markup Language, abbreviated: XML] markup refers to information symbols that computers can understand. Through this markup, computers can process Articles containing various information, etc.), the browser prints each dot and line by drawing them instead of filling certain spaces with predefined pixels. This ensures that SVG images can adapt to different screen sizes and resolutions.
  • Because they are defined in XML, SVG images are more flexible than JPG or PNG images, and we can interact with them using CSS and JavaScript. SVG image settings can contain CSS and JavaScript. Under the framework of data-driven views such as react and vue, it is even more comfortable for SVG operations. (The following will share with you some small SVG animation practice in our project)
  • On the application level, SVG provides some image editing effects, such as masking and cropping, applying filters and so on. And SVG is just text, so it can be effectively compressed using GZip.

6. Jquery animate()method

  • animate()method to perform CSSa custom animation of the property set.
  • This method changes an element from one state to another via CSS styles.
  • CSS property values ​​are changed gradually so that animation effects can be created.
  • Only numeric values ​​can be animated (such as " margin:30px"). String values ​​cannot be animated (such as " background-color:red").

Code demo:

<button id="btn1">使用动画放大高度</button>
<button id="btn2">重置高度</button>
<div id="box" style="background:#98bf21;height:100px;width:100px;margin:6px;">
</div>

$(document).ready(function(){
    $("#btn1").click(function(){
        $("#box").animate({height:"300px"});
    });
    $("#btn2").click(function(){
        $("#box").animate({height:"100px"});
    });
});

Renderings:

img

7. Use gifimages

Everyone must have touched the gif picture, and the front-end use is also very simple.

Summarize:

  • Simple animation in terms of code complexitycss : the code implementation will be simpler and jsmore complicated. For complex animations: cssthe code will become verbose and jsthe implementation will be better.
  • When the animation is running, the degree of control over the animation js is relatively flexible. It can control the animation pause, cancel, terminate and other cssanimations. Events cannot be added, and only fixed nodes can be set to perform transition animations.
  • Compatibility In most cases, cssthere is no browser compatibility problem .js
  • In terms of performance css , animation is relatively better. cssAnimation needs to be parsed by engine code before GUIparsing and rendering.jsjsGUI

2.26 Why does CSS not support parent selectors?

The answer to this question is the same as "Why does the CSS adjacent sibling selector only support the following elements, but not the previous sibling elements?"

Browsers parse HTML documents from front to back, from the outside to the inside. Therefore, we often see the loading situation where the header first appears on the page and then the main content appears again.

However, if CSS supports the parent selector, then all the child elements of the page must be loaded before rendering the HTML document, because the so-called "parent selector" means that the descendant elements affect the ancestor elements. If the descendant elements have not been loaded and processed, how will they affect Styles of ancestor elements? As a result, the rendering speed of the web page will be greatly slowed down, and the browser will display a long whiteboard. You can render as much HTML as you load, which is especially necessary when the network speed is not very fast. For example, for the article you are reading now, as long as the content of the article is loaded, even if the subsequent advertisement script blocks the loading of the subsequent HTML document, we can still read and experience it. However, if parent selectors are supported, the entire document cannot be blocked, and the accessibility of the page is greatly reduced.

Some people may say, should we not adopt the strategy of rendering wherever it is loaded? This is a bigger problem, because when loading into a child element, the style originally rendered by the parent element suddenly changes to another style, and the experience is very bad.

The same is true for "adjacent selectors can only select the elements behind". It is impossible to say that the HTML behind is loaded, and it will also affect the style of the previous HTML.

So, from this point of view, the possibility of CSS supporting "parent selector" or "pre-brother selector" is lower than other cool CSS features. It is not a technical level, but the rendering mechanism of CSS and HTML itself. decided. Of course, no one can say for sure what will happen in the future. Maybe in the future, the network speed will be a few G per second, and the web page loading speed will be completely negligible. Maybe it will be supported.

2.27 What are the ways to get out of the document flow?

1. What is document flow?

Divide the form into rows from top to bottom, and arrange elements in each row from left to right, which is called document flow, also known as ordinary flow.

This should not be difficult to understand. All elements in HTML are box models. Box models occupy a certain amount of space and are arranged in HTML in sequence to form a document flow.

Second, what is out of document flow?

After the element leaves the document flow, it will no longer occupy space in the document flow, but will be in a floating state (it can be understood as floating above the document flow). The positioning of elements out of the document flow is based on the normal document flow. When an element leaves the document flow, other elements still in the document flow will ignore the element and fill its original space.

3. How to break away from the document flow?

float

Use float to get out of document flow.

Notice! ! ! : When using float to leave the document flow, other boxes will ignore this element, but the text in other boxes will still make room for this element and wrap around it.

absolute

Absolute is called absolute positioning. In fact, the blogger thinks it should be called relative positioning, because the element after using absolute to break away from the document flow is relative to the parent class of the element (and above, if the direct parent class element does not meet the conditions, continue to query upwards ) element for positioning, and the position of this parent element must be non-static positioning (static is the default positioning method).

fixed

Completely out of document flow, positioning relative to the browser window. (relative to the browser window is relative to html).

2.28 What are css sprites and how to use them?

what is

CSS Sprites is a way of processing webpage image applications, which is to integrate some background images in a webpage into a single image file, and then use the combination of CSS "background-image", "background-repeat", and "background-position" Background positioning.

advantage

Its advantages are:

  • Reducing the http requests of web pages and improving performance is also the biggest advantage of CSS Sprites and the main reason why they are widely spread and applied;
  • Reduce the byte of the picture: the byte of multiple pictures combined into one picture is smaller than the sum of the bytes of multiple pictures;
  • Reduced naming troubles: only need to name a collection of pictures, no need to name every small element to improve production efficiency;
  • Easy to change styles: You only need to modify the color or style of pictures on one or a few pictures, and the style of the entire web page can be changed, which is more convenient to maintain.

shortcoming

It is true that CSS Sprites are so powerful, but there are also some shortcomings that cannot be ignored:

  • Image synthesis is more troublesome;
  • When setting the background, it is necessary to obtain the precise position of each background unit;
  • When maintaining composite images, it's best to just add images down rather than alter existing images.

2.29 What are the image loading and rendering rules in html and css?

The web browser first parses the acquired HTML code into a DOM tree. Each tag in the HTML is a node in the DOM tree, including the hidden tags with display: none, and the elements dynamically added by JavaScript. The browser will obtain all the styles and parse them into style rules, and remove the styles that the browser cannot recognize during the parsing process.

The browser will combine the DOM tree and style rules (DOM elements and style rules match) and then build a rendering tree (Render Tree). The rendering tree is similar to the DOM tree, but there is still a big difference between the two: rendering The tree can identify styles, each node (NODE) ​​in the rendering tree has its own style, and the rendering tree does not contain hidden nodes (such as display:none nodes, and some nodes inside), because these nodes will not use For rendering, it will not affect the rendering of nodes, so it will not be included in the rendering tree. Once the render tree is built, the browser can draw the page according to the render tree.

A simple summary is that the browser will go through six processes when rendering a Web page:

  • Parse HTML to form a DOM tree
  • Parse the loaded style and build a style rule tree
  • Load JavaScript, execute JavaScript code
  • The DOM tree and the style rule tree are matched to form a rendering tree
  • Calculate element position for page layout
  • Draw the page and finally render it in the browser

Do you feel that this has nothing to do with our image loading and rendering, but this is not the case, because img, picture or background-image are all part of the DOM tree or style rules, so when we apply them, there are timings for image loading and rendering It could be something like this:

  • When parsing HTML, if an img or picture tag is encountered, the image will be loaded
  • Parse the loaded style, when encountering background-image, the image will not be loaded, but a style rule tree will be built
  • Load JavaScript and execute JavaScript code. If there is an img element created in the code, it will be added to the DOM tree; if there is a background-image rule added, it will be added to the style rule tree
  • Build the rendering tree when the DOM tree matches the style rule, and if the DOM tree node matches the backgorund-image in the style rule, the background image will be loaded
  • Calculate element (image) position for layout
  • Start rendering the image, and the browser will render the rendered image

The browser's page rendering mechanism is applied above, but there are still certain rules for image loading and rendering. Because, not all (or picture) elements on the page will load the pictures and the background pictures introduced by background-image. Then a new question arises, when will it actually load, and what are the loading rules?

To summarize a bit:

Not all images in a web page will be loaded and rendered!

According to the browser loading and rendering mechanism introduced earlier, we can summarize it as:

  • , and when an element with background-image encounters display:none, the image will be loaded but not rendered
  • , and setting display:none on the ancestor element of the element that sets the background-image, the background-image will not be rendered or loaded, while the pictures introduced by img and picture will not be rendered but will be loaded
  • , and background-image import the same path and the same image file name, the image will only be loaded once
  • If the image introduced by background-image in the style file cannot match the DOM element, the image will not be loaded
  • The background-image introduced by the pseudo-class, such as: hover, only when the pseudo-class is triggered, the image will be loaded

2.30 What is BFC?

BFC: block formatting context, block-level formatting context.

The BFC is part of the visual CSS rendering of a web page, and is the area where the layout process for block boxes occurs, and where floated elements interact with other elements.

Positioning scheme:

  • The inner Boxes will be placed one after the other in the vertical direction.
  • The distance in the vertical direction of the Box is determined by the margin, and the margins of two adjacent Boxes belonging to the same BFC will overlap.
  • The left side of each element's margin box touches the left side of the containing block's border box.
  • The area of ​​the BFC will not overlap with the float box.
  • BFC is an isolated and independent container on the page, and the child elements inside the container will not affect the elements outside.
  • When calculating the height of BFC, floating elements will also participate in the calculation.

BFC can be triggered when one of the following conditions is met:

  • root element, ie html
  • The value of float is not None (default)
  • The value of overflow is not visible (default)
  • The display value is one of table-cell, table-caption, inline-block, flex, or inline-flex
  • The value of position is absolute or fixed

2.31 Analysis and comparison of opacity: 0, visibility: hidden, display: none advantages and disadvantages and applicable scenarios

structure

display:none: The element will completely disappear from the rendering tree, it will not occupy any space when rendering, and cannot be clicked

visibility: hidden: The element will not disappear from the rendering tree, and the rendering element continues to occupy space, but the content is invisible and cannot be clicked

opacity: 0: The element will not disappear from the rendering tree, and the rendering element continues to occupy space, but the content is invisible and can be clicked

inherit

display: none and opacity: 0: are non-inherited attributes, and the disappearance of descendant nodes is caused by the disappearance of elements from the rendering tree, which cannot be displayed by modifying the attributes of descendant nodes.

visibility: hidden: is an inherited attribute, and the descendant node disappears due to the inheritance of hidden. By setting visibility: visible; the descendant node can be made explicit.

performance

displaynone : Modifying the element will cause the document to reflow, and the screen reader will not read the content of the display: none element, which consumes a lot of performance

visibility:hidden: Modifying an element will only cause the element to be redrawn, which consumes less performance. The screen reader reads the content of the visibility: hidden element

opacity: 0 : modifying the element will cause redrawing, less performance consumption

2.32 What is Atom CSS?

Atom CSS: Atomic CSS means that a class only does one thing.

Different from the commonly used BEM rules, atomic css is split, and all CSS classes have a unique CSS rule. For example as follows

.w-full{
  width:100%;
}
.h-full{
  height:100%;
}

but not like this

.w&h-full{
  width:100%;
  height:100%;
}

When we use it, just write the class name directly

<html>
	<body>
    	<div id="app" class="w-full h-full">
        </div>
	</body>
</html>

Pros and Cons of Atomic CSS

  • advantage
    • Reduced css volume and improved css reuse
    • Reduce the complexity of naming
  • shortcoming
    • Increased memory cost. After splitting CSS into atoms, you must remember some classes before writing. Even if tailwindcss provides a complete tool chain, when you write background, you must remember that it starts with bg.
    • Increased the complexity of the html structure. When the entire dom has such a class name, it will inevitably bring troubles in debugging, and sometimes it is difficult to locate specific css problems
    • You still need a class name. For most attributes, you can only use center, auto, 100%, these values, but sometimes you still need to set different parameter values, such as left, top, at this time you also need to give a class name

2.33 What is the 1-pixel problem in CSS? What are the solutions?

The origin of the 1px border problem

Apple iPhone4 first proposed the concept of Retina Display (retina screen). In the retina screen used by iPhone4, 2x2 pixels are used as 1 physical pixel, that is, 2x2 pixels are used to display the content displayed by 1 physical pixel, so that The UI display is more refined and clear, and these 2x2 pixels are called logical pixels.

A retina screen with a pixel ratio of 2 (pixel ratio (ie dpr) = physical pixel/logical pixel) is also called a double screen. Currently, there are triple screens and quadruple screens with higher pixel ratios on the market.

In CSS, 1px refers to physical pixels. Therefore, the border set to 1px actually occupies the width of 2 logical pixels on the retina screen with dpr = 2, which leads to a visual experience of thicker interface borders.

Use transform to solve

By setting the element's box-sizing to border-box, then constructing a pseudo-element, and then using CSS3's transform to zoom, this is currently the most respected solution on the market. This method can satisfy all scenarios, and it can be modified flexibly. The only drawback is that an additional useless element needs to be nested for elements that have used pseudo-elements. The specific implementation is as follows:

.one-pixel-border {
  position: relative;
  box-sizing: border-box;
}

.one-pixel-border::before {
  display: block;
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 200%;
  height: 200%;
  border: 1px solid red;
  transform: translate(-50%, -50%) scale(0.5, 0.5);
}

This will give you a 0.5px border.

You can also combine media queries (@media) to solve the border problem of screens with different dpr values, as follows:

@media screen and (-webkit-min-device-pixel-ratio: 2), (min-resolution: 2dppx) {
  ...
}

@media screen and (-webkit-min-device-pixel-ratio: 3), (min-resolution: 3dppx) {
  ...
}

Of course, there are many other solutions: border-image, background-image, viewport + rem + js, box-shadow, etc., but they all have their own shortcomings, so they are not recommended and will not be introduced in detail here.

2.34 Will css loading cause blocking?

Let me talk about the conclusion first:

  • CSS loading will not block the parsing of the DOM tree
  • CSS loading will block the rendering of the DOM tree
  • css loading will block the execution of subsequent js statements

In order to prevent users from seeing a long white screen time, we should try to increase the css loading speed as much as possible. For example, the following methods can be used:

  • Use CDN (because CDN will select the nearest node with cached content to provide you with resources according to your network conditions, so it can reduce loading time)
  • Compress css (you can use many packaging tools, such as webpack, gulp, etc., or you can enable gzip compression)
  • Reasonable use of cache (setting cache-control, expires, and E-tag is good, but one problem to be aware of is that after the file is updated, you need to avoid the impact of the cache. One of the solutions is to prevent the file name followed by a version number)
  • Reduce the number of http requests, merge multiple css files, or simply write inline styles directly (one disadvantage of inline styles is that they cannot be cached)

Principle analysis

The browser rendering process is as follows:

  • HTML parses files to generate DOM Tree, parses CSS files to generate CSSOM Tree
  • Combine Dom Tree and CSSOM Tree to generate Render Tree (render tree)
  • Render the pixels to the screen according to the Render Tree rendering.

From the process we can see that:

  • DOM parsing and CSS parsing are two parallel processes, so this also explains why CSS loading does not block DOM parsing.
  • However, since Render Tree is dependent on DOM Tree and CSSOM Tree, it must wait until CSSOM Tree is built, that is, CSS resource loading is complete (or CSS resource loading fails), before rendering can start. Therefore, CSS loading will block the rendering of Dom.
  • 由于js可能会操作之前的Dom节点和css样式,因此浏览器会维持html中css和js的顺序。因此,样式表会在后面的js执行前先加载执行完毕。所以css会阻塞后面js的执行。

2.35 CSS 中有哪几种定位方式?

  • Static

这个是元素的默认定位方式,元素出现在正常的文档流中,会占用页面空间。

  • Relative

相对定位方式,相对于其父级元素(无论父级元素此时为何种定位方式)进行定位,准确地说是相对于其父级元素所剩余的未被占用的空间进行定位(在父元素由多个相对定位的子元素时可以看出),且会占用该元素在文档中初始的页面空间,即在使用top,bottom,left,right进行移动位置之后依旧不会改变其所占用空间的位置。可以使用z-index进行在z轴方向上的移动。

  • Absolute

绝对定位方式,脱离文档流,不会占用页面空间。以最近的不是static定位的父级元素作为参考进行定位,如果其所有的父级元素都是static定位,那么此元素最终则是以当前窗口作为参考进行定位。

可以使用top,bottom,left,right进行位置移动,亦可使用z-index在z轴上面进行移动。当元素为此定位时,如果该元素为内联元素,则会变为块级元素,即可以直接设置其宽和高的值;如果该元素为块级元素,则其宽度会由初始的100%变为auto。

注意:当元素设置为绝对定位时,在没有指定top,bottom,left,right的值时,他们的值并不是0,这几个值是有默认值的,默认值就是该元素设置为绝对定位前所处的正常文档流中的位置。

  • Fixed

绝对定位方式,直接以浏览器窗口作为参考进行定位。其它特性同absolute定位。

当父元素使用了transform的时候,会以父元素定位。

  • sticky

粘性定位,可以简单理解为relative和fixed布局的混合。

当粘性约束矩形在可视范围内为relative,反之,则为fixed粘性定位元素如果和它的父元素一样高,则垂直滚动的时候,粘性定位效果是不会出现的它的定位效果完全受限于父级元素们。

If the overflow attribute of the parent element is set to scroll, auto, and overlay values, then the sticky positioning will be invalid. Multiple pasted positioning elements in the same container are offset independently, so they may overlap; sticky positioning in different containers whose positions are close together up and down The elements will occupy the magpie's nest, crowding out the original elements, forming the effect of occupying places one by one.

2.36 If you need to write animation manually, how long do you think the minimum time interval is, and why?

The default frequency of most monitors is 60Hz, that is, refresh 60 times per second, so the theoretical minimum interval is 1/60*1000ms = 16.7ms.

2.37 What are the methods of CSS optimization and performance improvement?

  • avoid over restraint
  • Avoid descendant selectors
  • Avoid Chained Selectors
  • use compact syntax
  • Avoid unnecessary namespaces
  • avoid unnecessary repetition
  • It is better to use semantically expressive names. A good class name should describe what it is rather than what it looks like
  • avoid! important, you can choose other selectors
  • Keep rules as compact as possible, you can combine duplicate rules in different classes

2.38 What scenarios are margin and padding suitable for?

When to use margins:

  • Need to add white space outside the border
  • No background color required for white space
  • The blank space between two connected boxes needs to cancel each other out.

When to use padding:

  • Need to add whitespace inside the border
  • Background color is required for white space
  • The blank space of the two boxes connected up and down is expected to be the sum of the two.

2.39 Why do floats appear? When do floats need to be cleared? What are the ways to clear floats?

The floated element stops when it hits its containing border or the border of the floated element. Since the floated element is not in the document flow, the block box of the document flow behaves as if the floated box does not exist. Floated elements float over block boxes in the document flow.

Problems with floats:

  • The height of the parent element cannot be expanded, affecting elements at the same level as the parent element
  • Non-floated elements (inline elements) at the same level as floated elements will follow
  • If it is not the first element that floats, the elements before this element also need to float, otherwise it will affect the structure of the page display.

Ways to clear floats:

  • Parent div defines height
  • Add an empty div tag after the last floating element and add style clear:both.
  • Add style overflow to hidden or auto for the parent tag containing floating elements.
  • parent div defines zoom

2.40 What are the new pseudo-classes in CSS3?

  • p:first-of-type selects the first element belonging to its parent element
  • p:last-of-type selects the last element belonging to its parent element
  • p:only-of-type selects elements that are unique to their parent
  • p:only-child selects the only child element that belongs to its parent element
  • p:nth-child(2) selects the second child element belonging to its parent element
  • :enabled :disabled Disabled state of the form control.
  • :checked Radio or checkbox is checked.

2.41 In CSS, what is the use of the box-sizing attribute value?

The parsing mode used to control the box model of the element, the default is content-box

  • context-box: W3C's standard box model, setting the height/width attribute of the element refers to the height/width of the content part
  • border-box: IE traditional box model. The height/width attribute of the setting element refers to the height/width of the border + padding + content part

Using the box-sizing property can solve some common layout problems, and also improve the efficiency and maintainability of CSS code writing. For example, when we use relative units such as percentages or rem to set the size of elements, it is more appropriate to use border-box box model; and when dealing with some fixed size and need fine-grained control, content-box box model may be more appropriate. For practicality.

It should be noted that under different box-sizing settings, the element's size calculation method will change, and it is necessary to fully consider the impact of this property on layout and style when writing CSS code.

2.42 Why should CSS styles be initialized in front-end projects?

Due to browser compatibility issues, different browsers have different default values ​​for tags. If the browser's CSS is not initialized, it will cause differences in the display of the same page in different browsers.

2.43 What is the order of CSS matching rules?

I believe that most beginners will think that CSS matching is left to right, but it is actually the opposite.

CSS matching happens when the Render Tree is built (Chrome Dev Tools attributes it to the Layout process). At this time, the browser builds the DOM and gets the CSS style. What it needs to do at this time is to match the style with the nodes on the DOM. What the browser needs to do in order to improve performance is to quickly match.

首先要明确一点,浏览器此时是给一个"可见"节点找对应的规则,这和jQuery选择器不同,后者是使用一个规则去找对应的节点,这样从左到右或许更快。但是对于前者,由于CSS的庞大,一个CSS文件中或许有上千条规则,而且对于当前节点来说,大多数规则是匹配不上的,稍微想一下就知道,如果从右开始匹配(也是从更精确的位置开始),能更快排除不合适的大部分节点,而如果从左开始,只有深入了才会发现匹配失败,如果大部分规则层级都比较深,就比较浪费资源了。

除了上面这点,我们前面还提到DOM构建是"循序渐进的",而且DOM不阻塞Render Tree构建(只有CSSOM阻塞),这样也是为了能让页面更早有元素呈现。

考虑如下情况,如果我们此时构建的只是部分DOM,而CSSOM构建完成,浏览器就会构建Render Tree。

这个时候对每一个节点,如果找到一条规则从右向左匹配,我们只需要逐层观察该节点父节点是否匹配,而此时其父节点肯定已经在DOM上。

但是反过来,我们可能会匹配到一个DOM上尚未存在的节点,此时的匹配过程就浪费了资源。

2.44 如何使用css完成视差滚动效果?

一、是什么

视差滚动(Parallax Scrolling)是指多层背景以不同的速度移动,形成立体的运动效果,带来非常出色的视觉体验

我们可以把网页解刨成:背景层、内容层、悬浮层

当滚动鼠标滑轮的时候,各个图层以不同的速度移动,形成视觉差的效果

二、实现方式

使用css形式实现视觉差滚动效果的方式有:

  • background-attachment
  • transform:translate3D

background-attachment

作用是设置背景图像是否固定或者随着页面的其余部分滚动

值分别有如下:

  • scroll:默认值,背景图像会随着页面其余部分的滚动而移动
  • fixed:当页面的其余部分滚动时,背景图像不会移动
  • inherit:继承父元素background-attachment属性的值

Accomplishing scrolling parallax requires background-attachmentsetting the property to fixed, so that the background is fixed relative to the viewport. Even if an element has a scrolling mechanism, the background will not scroll with the content of the element

In other words, the background has been fixed at the initial position from the beginning

The core csscode is as follows:

section {
    height: 100vh;
}

.g-img {
    background-image: url(...);
    background-attachment: fixed;
    background-size: cover;
    background-position: center center;
}

The whole chestnut is as follows:

<style>
div {
            height: 100vh;
            background: rgba(0, 0, 0, .7);
            color: #fff;
            line-height: 100vh;
            text-align: center;
           font-size: 20vh;
        }

        .a-img1 {
            background-image: url(https://images.pexels.com/photos/1097491/pexels-photo-1097491.jpeg);
            background-attachment: fixed;
            background-size: cover;
            background-position: center center;
        }

        .a-img2 {
            background-image: url(https://images.pexels.com/photos/2437299/pexels-photo-2437299.jpeg);
            background-attachment: fixed;
            background-size: cover;
            background-position: center center;
        }

        .a-img3 {
            background-image: url(https://images.pexels.com/photos/1005417/pexels-photo-1005417.jpeg);
            background-attachment: fixed;
            background-size: cover;
            background-position: center center;
        }
</style>
 <div class="a-text">1</div>
    <div class="a-img1">2</div>
    <div class="a-text">3</div>
    <div class="a-img2">4</div>
    <div class="a-text">5</div>
    <div class="a-img3">6</div>
    <div class="a-text">7</div>

transform:translate3D

Again, let's look at two concepts transformand first perspective:

  • transform: css3 attribute, which can transform elements (2d/3d), including translate translate, rotate rotate, zoom scale, etc.
  • perspective: css3 attribute, when the element involves 3d transformation, perspective can define the 3d stereoscopic effect that our eyes see, that is, the sense of space

3DThe perspective diagram is as follows:

Take a chestnut:

<style>
    html {
        overflow: hidden;
        height: 100%
   }

    body {
        /* 视差元素的父级需要3D视角 */
        perspective: 1px;
        transform-style: preserve-3d; 
        height: 100%;
        overflow-y: scroll;
        overflow-x: hidden;
    }
    #app{
        width: 100vw;
        height:200vh;
        background:skyblue;
        padding-top:100px;
    }
    .one{
        width:500px;
        height:200px;
        background:#409eff;
        transform: translateZ(0px);
        margin-bottom: 50px;
    }
    .two{
        width:500px;
        height:200px;
        background:#67c23a;
        transform: translateZ(-1px);
        margin-bottom: 150px;
    }
    .three{
        width:500px;
        height:200px;
        background:#e6a23c;
        transform: translateZ(-2px);
        margin-bottom: 150px;
    }
</style>
<div id="app">
    <div class="one">one</div>
    <div class="two">two</div>
    <div class="three">three</div>
</div>

The principle of visual difference in this way is as follows:

  • Set transform-style: preserve-3d and perspective: xpx on the container, then the child elements in this container will be located in 3D space,
  • The sub-element sets different transform: translateZ(). At this time, the distance of different elements from the screen (our eyes) in the 3D Z-axis direction is also different.
  • Scrolling the scroll bar, since the sub-elements are set with different transform: translateZ(), the up and down distance of translateY relative to the screen (our eyes) is also different, which achieves the effect of scrolling parallax

2.45 How to implement the ellipsis style for single-line/multi-line text overflow?

2. Implementation method

Single line text overflow omitted

The understanding is also very simple, that is, the text is displayed in one line, and the excess part is displayed in the form of ellipsis

The implementation method is also very simple, and the attributes involved cssare:

  • text-overflow: specifies that when the text overflows, an ellipsis is displayed to represent the trimmed text
  • white-space: Set the text to be displayed on one line, and cannot wrap
  • overflow: If the length of the text exceeds the limited width, the excess content will be hidden

overflow设为hidden,普通情况用在块级元素的外层隐藏内部溢出元素,或者配合下面两个属性实现文本溢出省略

white-space:nowrap,作用是设置文本不换行,是overflow:hiddentext-overflow:ellipsis生效的基础

text-overflow属性值有如下:

  • clip:当对象内文本溢出部分裁切掉
  • ellipsis:当对象内文本溢出时显示省略标记(…)

text-overflow只有在设置了overflow:hiddenwhite-space:nowrap才能够生效的

举个例子

<style>
    p{
        overflow: hidden;
        line-height: 40px;
        width:400px;
        height:40px;
        border:1px solid red;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
</style>
<p 这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本</p >

可以看到,设置单行文本溢出较为简单,并且省略号显示的位置较好

多行文本溢出省略

多行文本溢出的时候,我们可以分为两种情况:

  • 基于高度截断
  • 基于行数截断

基于高度截断

伪元素 + 定位

核心的css代码结构如下:

  • position: relative:为伪元素绝对定位
  • overflow: hidden:文本溢出限定的宽度就隐藏内容)
  • position: absolute:给省略号绝对定位
  • line-height: 20px:结合元素高度,高度固定的情况下,设定行高, 控制显示行数
  • height: 40px:设定当前元素高度
  • ::after {} :设置省略号样式

代码如下所示:

<style>
    .demo {
        position: relative;
        line-height: 20px;
        height: 40px;
        overflow: hidden;
    }
    .demo::after {
        content: "...";
        position: absolute;
        bottom: 0;
        right: 0;
        padding: 0 20px 0 10px;
    }
</style>

<body>
    <div class='demo'>这是一段很长的文本</div>
</body>

实现原理很好理解,就是通过伪元素绝对定位到行尾并遮住文字,再通过 overflow: hidden 隐藏多余文字

这种实现具有以下优点:

  • 兼容性好,对各大主流浏览器有好的支持
  • 响应式截断,根据不同宽度做出调整

一般文本存在英文的时候,可以设置word-break: break-all使一个单词能够在换行时进行拆分

基于行数截断

css实现也非常简单,核心的css代码如下:

  • -webkit-line-clamp: 2:用来限制在一个块元素显示的文本的行数,为了实现该效果,它需要组合其他的WebKit属性)
  • display: -webkit-box:和1结合使用,将对象作为弹性伸缩盒子模型显示
  • -webkit-box-orient: vertical: Used in conjunction with 1 to set or retrieve the arrangement of the child elements of the flex box object
  • overflow: hidden: the text overflows the limited width to hide the content
  • text-overflow: ellipsis: In the case of multi-line text, use the ellipsis "..." to hide the overflowing text
<style>
    p {
        width: 400px;
        border-radius: 1px solid red;
        -webkit-line-clamp: 2;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
    }
</style>
<p>
    这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本
    这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本
</p >

It can be seen that the attribute extension used above is compatible with the browsers with the kernel of the terminal . Since most of the mobile terminals are used webkit, this form is commonly used on the mobile terminal.CSSPCwebkitwebkit

It should be noted that if the text is a long piece of English or numbers, you need to add word-wrap: break-wordattributes

It can also be used to javascriptachieve cooperation css, and the implementation code is as follows:

The css structure is as follows:

p {
    position: relative;
    width: 400px;
    line-height: 20px;
    overflow: hidden;

}
.p-after:after{
    content: "..."; 
    position: absolute; 
    bottom: 0; 
    right: 0; 
    padding-left: 40px;
    background: -webkit-linear-gradient(left, transparent, #fff 55%);
    background: -moz-linear-gradient(left, transparent, #fff 55%);
    background: -o-linear-gradient(left, transparent, #fff 55%);
    background: linear-gradient(to right, transparent, #fff 55%);
}

The javascript code is as follows:

$(function(){
 //获取文本的行高,并获取文本的高度,假设我们规定的行数是五行,那么对超过行数的部分进行限制高度,并加上省略号
   $('p').each(function(i, obj){
        var lineHeight = parseInt($(this).css("line-height"));
        var height = parseInt($(this).height());
        if((height / lineHeight) >3 ){
            $(this).addClass("p-after")
            $(this).css("height","60px");
        }else{
            $(this).removeClass("p-after");
        }
    });
})

2.46 How to use CSS3 to achieve animation?

1. What is it?

CSS Animations (CSS Animations) is a module proposed for Cascading Style Sheets that allows the animation of Extensible Markup Language (XML) elements using CSS

Refers to the process of gradually transitioning an element from one style to another

There are many common animation effects, such as translation, rotation, scaling, etc., and a complex animation is a combination of multiple simple animations

cssThere are several ways to implement animation:

  • transition implements gradient animation
  • transform transform animation
  • animation implements custom animation

2. Implementation method

transition implements gradient animation

transitionThe properties are as follows:

  • property: fill in the css properties that need to be changed
  • duration: the time unit required to complete the transition effect (s or ms)
  • timing-function: the speed curve to complete the effect
  • delay: The delayed trigger time of the animation effect

The timing-functionvalues ​​are as follows:

value describe
linear Uniform velocity (equal to cubic-bezier(0,0,1,1))
ease From slow to fast to slow (cubic-bezier(0.25,0.1,0.25,1))
ease-in Slowly becomes faster (equal to cubic-bezier(0.42,0,1,1))
ease-out Gradually get slower (equal to cubic-bezier(0,0,0.58,1))
ease-in-out Faster first and then slower (equal to cubic-bezier(0.42,0,0.58,1)), fade in and out
cubic-bezier(n,n,n,n) Define your own values ​​in the cubic-bezier function. Possible values ​​are numeric values ​​between 0 and 1

Note: Not all attributes can use transitions, such asdisplay:none<->display:block

For example, to realize the animation effect of mouse moving up and changing

<style>
       .base {
    
    
            width: 100px;
            height: 100px;
            display: inline-block;
            background-color: #0EA9FF;
            border-width: 5px;
            border-style: solid;
            border-color: #5daf34;
            transition-property: width, height, background-color, border-width;
            transition-duration: 2s;
            transition-timing-function: ease-in;
            transition-delay: 500ms;
        }

        /*简写*/
        /*transition: all 2s ease-in 500ms;*/
        .base:hover {
    
    
            width: 200px;
            height: 200px;
            background-color: #5daf34;
            border-width: 10px;
            border-color: #3a8ee6;
        }
</style>
<div class="base"></div>

transform transform animation

Contains four commonly used functions:

  • translate: displacement
  • scale: scaling
  • rotate: rotate
  • skew: tilt

general fit transitionoveruse

Note that elements transformare not supported inline, change it toblock

for example

<style>
    .base {
        width: 100px;
        height: 100px;
        display: inline-block;
        background-color: #0EA9FF;
        border-width: 5px;
        border-style: solid;
        border-color: #5daf34;
        transition-property: width, height, background-color, border-width;
        transition-duration: 2s;
        transition-timing-function: ease-in;
        transition-delay: 500ms;
    }
    .base2 {
        transform: none;
        transition-property: transform;
        transition-delay: 5ms;
    }

    .base2:hover {
        transform: scale(0.8, 1.5) rotate(35deg) skew(5deg) translate(15px, 25px);
    }
</style>
 <div class="base base2"></div>

You can see that the box has been rotated, tilted, translated, and zoomed in

animation implements custom animation

animationIt is an abbreviation of 8 attributes, which are as follows:

Attributes describe attribute value
animation-duration Specify the time required for the animation to complete a cycle, in seconds (s) or milliseconds (ms), the default is 0
animation-timing-function Specify the animation timing function, that is, the speed curve of the animation, the default is "ease" linear、ease、ease-in、ease-out、ease-in-out
animation-delay Specifies the animation delay time, that is, when the animation starts, the default is 0
animation-iteration-count Specify the number of times to play the animation, the default is 1
animation-direction specifies the direction in which the animation will play The default is normal normal、reverse、alternate、alternate-reverse
animation-fill-mode Specifies the animation fill mode. The default is none forwards、backwards、both
animation-play-state Specifies the animation playback state, running or paused. The default is running running、breaks
animation-name Specifies the name of the @keyframes animation

CSSThe animation only needs to define some key frames, and the browser will interpolate and calculate the rest of the frames according to the timing function.

@keyframesKeyframes are defined by

So, if we want the element to rotate in a circle, we only need to define the start and end two frames:

@keyframes rotate{
    from{
        transform: rotate(0deg);
    }
    to{
        transform: rotate(360deg);
    }
}

fromIndicates the frame at the beginning and tothe frame at the end

You can also use percentages to describe the life cycle

@keyframes rotate{
    0%{
        transform: rotate(0deg);
    }
    50%{
        transform: rotate(180deg);
    }
    100%{
        transform: rotate(360deg);
    }
}

After defining the keyframe, you can use it directly:

1animation: rotate 2s;

3. Summary

Attributes meaning
transition (excessive) It is used to set the excessive style of the element, which has a similar effect to animation, but the details are very different
transform It is used to rotate, scale, move or tilt the element, and it has nothing to do with the animation of the style. It is equivalent to color to set the "appearance" of the element
translate (move) It's just an attribute value of transform, that is, to move
animation Used to set animation properties, he is a shorthand property, including 6 properties

2.47 em/px/rem/vh/vw What is the difference between these units?

1. Introduction

In traditional project development, we only use px, %, and emthese units, which can be applied to most project development and have relatively good compatibility

From CSS3the beginning, the browser's support for measurement units has been raised to another level, and some new measurement units such as rem, vh, vw, etc. have been addedvm

Use these new units to develop relatively good responsive pages, adapting to terminals with different resolutions, including mobile devices, etc.

2. Unit

In cssunits, it can be divided into length units, absolute units, as indicated in the table below

css unit
relative length unit em, ex, ch, rem, vw, vh, vmin, vmax, %
absolute unit of length cm、mm、in、px、pt、pc

Here we mainly talk about px, em, rem, vh, vw

px

px, stands for pixel. The so-called pixel is a small point presented on our display. Each pixel is the same size, so the pixel is a unit of measurement and is divided into absolute length units.

Some people pxthink it is a relative length, because there is a device pixel ratio in the mobile terminal, and the pxactual displayed size is uncertain

The reason why it is considered pxan absolute unit is that pxthe size of the element has nothing to do with other attributes of the element

em

em is a relative unit of length. Relative to the font size of the text within the current object. If the current font size of the inline text is not manually set, it is relative to the default font size of the browser ( 1em = 16px)

To simplify font-sizethe conversion of the , we need to declare = in the selector in cssthe , which makes the em value becomebodyfont-size62.5%16px*62.5% = 10px

In this way 12px = 1.2em, 10px = 1em, that is to say, you only need to divide your original pxvalue by 10, and then replace it em as the unit

Features:

  • The value of em is not fixed
  • em will inherit the font size of the parent element
  • em is a relative length unit. Relative to the font size of the text within the current object. If the current font size of the inline text is not manually set, it is relative to the default font size of the browser
  • The default font height of any browser is 16px

for example

<div class="big">
    我是14px=1.4rem
    <div class="small">我是12px=1.2rem</div>
</div>

style as

<style>
html {font-size: 10px;  } /*  公式16px*62.5%=10px  */  
.big{font-size: 1.4rem}
.small{font-size: 1.2rem}
</style>

At this time, .bigthe element font-sizeis 14px, and .smallthe element font-sizeis 12px

rem

rem, relative unit, relative is just font-sizethe value of HTML root element

Similarly, if we want simplified font-sizeconversion, we can htmladd to the root elementfont-size: 62.5%

html {font-size: 62.5%;  } /*  公式16px*62.5%=10px  */ 

In this way, 1rem=10px, 1.2rem=12px, 1.4rem=14px, 1.6rem=16px in the page; so that the vision, use and writing have been greatly helped

Features:

  • The rem unit can be described as combining the advantages of relative size and absolute size
  • The difference from em is that rem is always relative to the root element, unlike em, which uses a cascade method to calculate the size

vh、vw

vw is divided into 100 equal parts according to the width of the window, 100vw means full width, and 50vw means half width. (vw is always the width of the window), similarly, vhit is the height of the window

The windows here are divided into several situations:

  • On the desktop, the viewable area of ​​the browser
  • The mobile terminal refers to the layout viewport

Like vw, vh, one of the more confusing units is %, but the percentage is broadly relative to the parent element:

For ordinary positioning elements, it is the parent element we understand

  • For position: absolute; elements are relative to the positioned parent element
  • For position: fixed; elements are relative to ViewPort (visual window)

3. Summary

px : Absolute unit, the page is displayed in precise pixels

em : relative unit, the reference point is the font size of the parent node, if it is defined by itself , it is not a fixed value font-sizein the entire page1em

rem : relative unit, which can be understood as calculating root emrelative to the font size of the root nodehtml

vh, vw : Mainly used for page viewport size layout, which is more convenient and simple in page layout

Guess you like

Origin blog.csdn.net/hyqhyqhyqq/article/details/130649407