Source: making stars ✨ | o | give a ❤ ️ attention, ❤ ️ thumb up, ❤ ️ encourages the author

preface

I hope I can get help for you through this article. (Thanks for one button three times)

Still learning TypeScript

TS: language built on JavaScript; Can be executed on platforms that support JavaScript; A superset of JavaScript, TypeScript extends JavaScript and adds types; TS cannot be executed directly by the JS parser.

TypeScript adds types, supports new features in ES, adds new features that ES doesn’t have, rich configuration options, and powerful development tools.

To learn TS, download Node.js

Use NPM to install typescript globally. Enter NPM I -g typescript to create a TS file and compile the TS file using TSC. Go to the command line, go to the directory where the TS file is stored, and run TSC xxx.ts.

Basic types:

Type declaration:

  • Type declarations are a very important feature of TS
  • The type declaration allows you to specify the type of a variable in TS
  • After the type is specified, the TS compiler automatically checks if the bit variable is assigned a value that matches the type declaration. Otherwise, an error is reported
  • In short, a type declaration sets the type of a variable so that it can only store values of a certain type

Grammar:

Let variable: type; Let variable: type = value; Function fn(parameter: type, parameter: type) : type {... }Copy the code

Automatic type determination:

  • TS has an automatic type determination mechanism
  • When a variable is declared and assigned simultaneously, the TS compiler automatically determines the type of the variable
  • So if your variable is declared and assigned at the same time, you can omit the type declaration
type describe
number Any Numbers
string Arbitrary string
boolean Boolean value true or false
literal The value of the constraint variable is the value of the literal
any Any type
unknown Type safe any
void No value or undefined
never No value can’t be any value
object Any JS object
array Arbitrary JS array
tuple Element, TS new type, fixed length array
enum Enumeration, new type in TS
  • number
let decimal: number = 6;
let hex: number = 0xf00d;
Copy the code
  • boolean
let isDone: boolean = false;
Copy the code
  • string
let color: striing = "blue"'
color = "red";
let fullName: string = "jeskson";
Copy the code
  • literal
let color: 'red' | 'blue' | 'black';
Copy the code
  • any
let d: any = 3;
d = 'jeskson';
Copy the code
  • unknown
let notSure: unknown = 4;
Copy the code
  • void
let unusable: void = undefined;
Copy the code
  • never
function error(message: string): never {
 throw new Error(message);
}
Copy the code
  • object
let obj: object = {}
Copy the code
  • array
Let list: number[] = [1,2,3]; Let list: Array<number> = [1,2,3];Copy the code
  • tuple
let x: [string, number];
x = ["hello", 10];
Copy the code
  • Types of assertions

In some cases, the type of the variable is clear to us, but not to the TS compiler. In this case, we can tell the compiler the type of the variable using a type assertion, which can take two forms:

  • The first:
let someValue: unknown = "jeskson 1024bibi.com";
let strlength: number = (someValue as string).length;
Copy the code
  • The second:
let someValue: unknown = "1024bibi.com";
Copy the code

Compiler options

  • Auto-compile file

When compiling a file, using the -w command, the TS compiler automatically monitors the file for changes and recompiles the file if it changes.

tsc xxx.ts -w
Copy the code
  • Automatically compile the entire project:

If you use the TSC directive directly, you can automatically compile all ts files under the current project into JS files.

To use the TSC command directly, you must create a tsconfig.json configuration file in the root directory of the project.

Tsconfig. json is a JSON file. After adding the configuration file, you only need TSC to compile the entire project.

Configuration options:

Include: Defines the directory in which you want the files to be compiled

/ / tsconfig. Json {" include: "[". / SRC / * * / *"]} / / / / * * * any directory arbitrary filesCopy the code

All files in the SRC directory and tests directory are compiled

"include": ["src/**/*", "tests/**/*"]
Copy the code
  • exclude

Define directories to be excluded; The default [” node_modules “, “bower_components”, “jspm_package”]

"exclude": ["./src/hello/**/*"]
Copy the code

SRC files in the Hello directory are not compiled

  • Extends: Defines the inherited configuration file
"extends": "./configs/base"
Copy the code

The current configuration file automatically contains all the configuration information in base.json in the config directory

  • files

Specifies the list to compile, used only when there are fewer files to compile

Example:

"files": [
 "type.ts",
 "dada.ts"
]
Copy the code
  • compilerOptions

Compile options are important and complex configuration options in configuration files

Contains suboptions to configure compilerOptions

Project option: Target

Sets the target version for ts code compilation

Example:

"compilerOptions": {
 "target": "ES6"
}
Copy the code

As set up above, the TS code we wrote will compile to the ES6 version of JS code

  • lib

Specifies the libraries included in the code runtime

"compilerOptions": {
 "target": "ES6",
 "lib": ["ES6", "DOM"],
 "outDir": "dist",
 "outFile": "dist/aa.js"
}
Copy the code

module

Sets up the modular system used by compiled code

"NoEmitOnError ": true, "alwayStrict": "noEmitOnError": true, "alwayStrict": True, // do not allow implicit any type "noImplicitAny": true, // do not allow undefined this "noImplicitThis": true, // strictNullChecks": trueCopy the code

Use WebPack to package your code

Use the NPM init -y command

Use: CNPM I -d webpack webpack-cli typescript TS-loader

// webpack.config.js // introduce a package const path = require('path'); Module. exports = {// specify the entry file: "./ SRC /index.ts", // specify the directory where the package file is located. Resolve (__dirname, 'dist'), filename: "bundle.js"}, // Specify the webpack package to use the module module: Rule: [{// test specifies the file in which the rule takes effect test: /\. Ts $/, // Specifies the Loader to use use: 'ts-loader', // specifies the file to exclude: /node-modules/ } ] } };Copy the code
// tsconfig.json
{
 "compilerOptions": {
  "module": "ES2015",
  "target": "ES2015",
  "strict" true
 }
}
Copy the code
// package.json

"scripts": {
 ...
 "bulid": "webpack"
}
Copy the code

Use the command line: NPM run build

webpack

Generally, we need to use the build tool to package the code in the actual development. TS can also be used with the build tool. The following uses webpack as an example to introduce how to use TS with the build tool.

Steps:

  • Initialize the project

Go to the root directory of the project and run the NPM init -y command to create a package.json file.

  • Download the build tool

npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin

npm i -D webpack webpack-cli typescript ts-loader
Copy the code
  • Webpack: Build tool Webpack
  • Webpack-cli: Command line tool for Webpack
  • Webpack-dev-server: development server for Webpack
  • Typescript: TS compiler
// webpack.config.js const HTMLWebpackPlugiin = require('html-webpack-plugin'); const {CleanWebpackPlugin} = require('clean-webpack-plugin'); Plugins: [new CleanWebpackPlugin(), new HTMLWebpackPlugin({title: Resolve: {extensions: ['.ts', '.js']}Copy the code
// package.json
"script": {
 ...
 "start": "webpack serve --open chrome.exe"
},
Copy the code

Run the CNPM I -d @babel/ core@babel /preset-env babel-loader core-js command

// use the webpack module: {// use the webpack module: {// Use the webpack module: {// Use the webpack module: {// Use the webpack module: {// Use the webpack module: { "Babel-loader ", // set Babel options: {presets: [[// Specifies the environment of the plugin "@babel/preset-env", // configuration information {targets: { "chrome":"88" } "corejs": "3", // use corejs usage to load "useBuiltIns":"usage"}]]}} 'ts-loader'] // exclude: /node-modules/}]}Copy the code

object-oriented

Object orientation is a very important idea in the program. It is understood by many students as a difficult and profound problem. In fact, object-oriented is very simple, all operations in the program need to be completed through objects.

Such as:

  • To manipulate the browser, use the Window object
  • To manipulate a web page, use the Document object
  • The operation console uses the console object

Everything goes through objects, so called object orientation, so what exactly is an object? This is to talk about what the program is, the essence of the computer program is the abstraction of real things, the antonym of abstraction is concrete, for example: a photo is the abstraction of a concrete person, a car model is the abstraction of a concrete car and so on. Programs are also abstractions of things, in which we can represent a person, a dog, etc. An object becomes an object in a program.

class

Define the class:

Class Class name {attribute name: type; Constructor (){this. Attribute name = parameter; } Method name (){... }}Copy the code

Example:

Class Person {// Const per = new Person(); // person. age // readonly attributes represent read-only attributes // define instance attributes name: string = 'jeskson'; Static age: number = 18; static age: number = 18; } const per = new Person(); // console.log(per); // console.log(per.name, per.age); sayHello(){ console.log('hello'); } // Without static, instance objects call // define static, class methods or propertiesCopy the code

The constructor

class Dog{
 name = 'j';
 age = 1;
 bark(){
  alert('j');
 }
}

const dog = new Dog();
const dog2 = new Dog();

console.log(dog);
console.log(dog2);
Copy the code

Modification:

class Dog { name: string; age: number; // Constructor calls constructor(name: string, age:) when the object is created. // This can be used to add the attribute this.name = name to the new object; // This can be used to add the attribute this.name = name to the new object. this.age = age; } bark() { alert('1024bibi.com'); Console.log (this.name); // This can be used in a method to represent the object on which the method is currently called. } } const dog = new Dog('dadaqianduan.cn', age: 1); const dog2 = new Dog('1024bibi.com', age: 2); console.log(dog); console.log(dog2); dog2.bark();Copy the code

inheritance

(function(){// define a class that represents a Dog. age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } sayHello() { console.log('dadaqianduan.cn')' } } const dog = new Dog('dada', 1); console.log(dog); dog.sayHello(); }) ();Copy the code

Using inheritance, subclasses have all the methods and attributes of their parent class

Using inheritance, you can write code that is common to multiple classes in a single parent class so that all subclasses have properties and methods in the parent class with only one write.

A subclass that overrides a method of its parent class is called method rewriting.

class Dog extends Animal{ run() { console.log(); } sayHello() { console.log(); }}Copy the code

Super – Another name for a superclass is superclass

(function(){ class Animal{ name: string; constructor(name: string) { this.name = name; } sayHello() {console.log(' animal calls '); }} class Dog extends Animal{sayHello() {super means super.sayHello(); } } const dog = new Dog('1024bibi.com'); dog.sayHello(); }) ();Copy the code
class Dog extends Animal{ age: number, constructor(name: string, age: Number){// If you write a constructor in a subclass, you must reference super(name) in the subclass constructor; // Call the parent constructor this.age = age; } super.sayHello() {// super.sayHello(); } } const dog = new Dog('dadaqianduan.cn');Copy the code

An abstract class

Classes that begin with abstract are abstract classes that are not expected to create objects

Abstract methods can be added to an abstract class. Abstract methods can only be defined in the abstract class, and subclasses must override the abstract method

abstract class Animal{ name: string; constructor(name: string) { this.name = name; } // Define an abstract method. // An abstract method starts with abstract, and has no body. // An abstract method can only be defined in an abstract class. }Copy the code

interface

MyType = {name: string, age: number}; // Interface is used to define a class structure. // Interface is used to define what attributes and methods a class should contain. // Interface is also used as a type declaration. age: number; } interface myInterface{ gender: string; } const obj: myType = { name: 'dada', age: 1 }; Const obj1: myInterface = {name: 'dada', age: 1, gender: 'male'}; }) ();Copy the code

Interfaces can restrict the structure of a class when defining it

None of the attributes in the interface can have actual values

An interface defines only the structure of an object, regardless of its actual value

All methods in the interface are abstract methods

interface myInter{ name: string; sayHello(): void; // implements myInter {class MyClass implements myInter {name: string; constructor(name: stirng) { this.name = name; SayHello (){sayHello(){sayHello(){sayHello(){Copy the code

encapsulation

(function(){// Define a Person class {private _name: string; private _age: number; // Private private attributes can be accessed only within the class. // Make private attributes accessible externally by adding methods to the class. string, age: number) { this._name = name; this._age = age; } getName() {return this._name; } setName(value: string) {if(value>=0) {this._name = value; }} // get name() {console.log('get name() performed '); return this._name; } set age(value) { if(value>=0){ this._age = value; } } } } const per = new Person('jeskson', 18); console.log(per); // per.name = 'dadaqianduan.cn'; // per.age = 12; // console.log(per.getName()); // per.setName('jeskson'); // per.age = 2 })();Copy the code
get name() {
 return this._name;
}

set name(value) {
 this._name = value;
}
Copy the code

public

class A { public num: number; // private num: number; // protected attributes. Constructor (num: number){this.num = num; } } class B extends A { test() { console.log(this.num); }}Copy the code

Syntactic sugar

Constructor (public name: string, public age: number){}}Copy the code

The generic

When defining functions or classes, you can use generics if the type is unclear

function fn(a: number): number{
 return a;
}
Copy the code

This is where generics come into play;

Here’s an example:

function test(arg: any): any{
    return arg;
}
Copy the code
  • Any turns off checking for any type

Using any turns off type checking for TS, and it also does not reflect that the parameter and return value are of the same type.

Create generic functions

Function fn<T>(a: T): T{return a; } // T can only be defined when the function is executedCopy the code


is a generic type, not necessarily called T

Functions with generics can be called directly

fn(10); Fn <string>('jeskson'); Function fn2<T,k>(a: T, b: k): T {console.log(b); return a; } fn2<number, string>(123, 'dadaqianduan.cn'); Interface Inter {length: number; } function fn3<T extends Inter>(a: T): number{ return a.length; } fn3('123'); fn3({length: 12);Copy the code

Generics can specify more than one class at a time. T extends Inter means that a generic type must implement an Inter class (subclass)

A generic class

class MyClass<T> {
 name: T;
 constructor(name: T) {
  this.name = name;
 }
}

const mc = new MyClass<string>('jeskson');
Copy the code

Typescript packaging

Webpack integration, usually in real development we need to use build tools to package the code; TS can also be used with build tools. The following uses webpack as an example to introduce how to build tools using TS:

To initialize the project, go to the project root directory and run the NPM init -y command to create package.json file.

To download the build tool, run the following command:

npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin
Copy the code
  • webpack: Build toolswebpack
  • webpack-cli:webpackCommand line tool
  • webpack-dev-server:webpackDevelopment server
  • typescript:tsThe compiler
  • ts-loader:tsLoader for compiling TS files in webpack
  • html-webpack-plugin:webpackHTML plug-in for automatic creation of HTML files
  • clean-webpack-plugin:webpackThe directory is cleared first with each build

Configuration webpack

Create webpack configuration file webpack.config.js in root directory:

const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); Module. exports = {optimization:{minimize: false}, entry: "./ SRC /index.ts", devtool: {optimization:{minimize: false}, entry: "./ SRC /index.ts" "inline-source-map", devServer: { contentBase: './dist' }, output: { path: path.resolve(__dirname, "dist"), filename: "Bundle. js", environment: {arrowFunction: false // close webpack arrowFunction, optional}}, resolve: {extensions: [".ts", ".js"] }, module: { rules: [ { test: /\.ts$/, use: { loader: "ts-loader" }, exclude: /node_modules/}]}, plugins: [new CleanWebpackPlugin(), new HtmlWebpackPlugin({title:'TS test '}),]}Copy the code

Configure TS compilation options

Tsconfig. json is created in the root directory and can be configured according to your needs

{
   "compilerOptions": {
       "target": "ES2015",
       "module": "ES2015",
       "strict": true
   }
}
Copy the code

Modify package.json configuration

"scripts": {
   "test": "echo \"Error: no test specified\" && exit 1",
   "build": "webpack",
   "start": "webpack serve --open chrome.exe"
},
Copy the code

Projects using

Create the ts file under SRC and run the NPM run build command line to compile the code.

Or run NPM start to start the development server;

Babel

In addition to WebPack, Babel is often used in development to transform code; To make it compatible with more browsers, follow these steps to introduce Babel into the project.

Promise and other ES6 features, TS can not directly convert, then use Babel to do the conversion.

Install dependency packages:

npm i -D @babel/core @babel/preset-env babel-loader core-js
Copy the code

A total of 4 packages are installed, which are:

Babel /core: The core tool of Babel

@babel/preset-env: Preset environment of Babel

@babel-loader: loader for Babel in webpack

Core-js: Core-js is used to enable older browsers to support the new ES syntax

Modify the webpack.config.js configuration file

module: {
    rules: [
        {
            test: /\.ts$/,
            use: [
                {
                    loader: "babel-loader",
                    options:{
                        presets: [
                            [
                                "@babel/preset-env",
                                {
                                    "targets":{
                                        "chrome": "58",
                                        "ie": "11"
                                    },
                                    "corejs":"3",
                                    "useBuiltIns": "usage"
                                }
                            ]
                        ]
                    }
                },
                {
                    loader: "ts-loader",

                }
            ],
            exclude: /node_modules/
        }
    ]
}
Copy the code

Files compiled using TS are processed again by Babel; Make the code usable in most browsers; You can also specify the browser version to be compatible with on the Targets TAB of the configuration option

Compiler options

Auto-compile file

tsc xxx.ts -w
Copy the code

Automatically compile the entire project

If you use the TSC directive directly, you can automatically compile all ts files under the current project into JS files.

To use the TSC command directly, you must create a tsconfig.json configuration file in the root directory of the project

Tsconfig. json is a JSON file. After adding the configuration file, you only need TSC command to complete the compilation of the entire project

include

Defines the directory where you want the files to be compiled

Default value: [] "* * / *" example: "include:" ["/SRC / * * * ", "tests / * * / *"]Copy the code

exclude

Define the directories that need to be excluded

Default value: [" node_modules bower_components ", ""," jspm_packages] "example:" exclude ": [". / SRC/hello / * * / *"]Copy the code

extends

Define inherited configuration files

Example: "extends": "./configs/base"Copy the code

files

Specifies a list of files to compile, used only when there are fewer files to compile

compilerOptions

Compile options are important and complex configuration options in configuration files

"compilerOptions": { "target": Optional values: ES3 (default), ES5, ES6/ES2015, ES7/ES2016, ES2017, ES2018, ES2019, ES2020, ESNextCopy the code

lib

Specify the libraries (host environment) that the code runtime contains

"compilerOptions": { "target": "ES6", "lib": ["ES6", "DOM"], "outDir": "dist", "outFile": "Dist /aa.js"} // Optional values: ES5, ES6/ES2015, ES7/ES2016, ES2017, ES2018, ES2019, ES2020, ESNext, DOM, WebWorker, ScriptHost......Copy the code

module

Sets up the modular system used by compiled code

"compilerOptions": {
    "module": "CommonJS"
}
Copy the code

outDir

The directory where the compiled file resides

"compilerOptions": {
    "outDir": "dist"
}
Copy the code

outFile

Compile all files into a JS file

By default, all code written in the global scope is merged into a JS file, and modules are merged together if the Module specifies None, System, or AMD

"compilerOptions": {
    "outFile": "dist/app.js"
}
Copy the code

rootDir

Specify the root directory for your code. By default, the compiled file’s directory structure takes the longest public directory as the root directory

// You can manually specify the root directory "compilerOptions": {"rootDir": "./ SRC "}Copy the code

allowJs

Whether to compile js files

checkJs

Whether to check the JS file

"compilerOptions": {
    "allowJs": true,
    "checkJs": true
}
Copy the code

removeComments

  • Delete comments
  • Default value: false

noEmit

  • The code is not compiled
  • Default value: false

sourceMap

  • Whether to generatesourceMap
  • Default value:false

Strict inspection

Strict enables all strict checks, default is true, AlwaysStrict always compiles code in strict mode noImplicitAny Disallows implicit any type noImplicitThis disallows this strictBindCallApply if the type is unclear Strictly check the bind, call, and the apply of the argument list strictFunctionTypes strictly check function type strictNullChecks strict null check whether strictPropertyInitialization strict inspection attribute initializationCopy the code

Additional inspection

noFallthroughCasesInSwitch

Check that the switch statement contains the correct break

noImplicitReturns

Check that the function has no implicit return value

noUnusedLocals

Check for unused local variables

noUnusedParameters

Check for unused parameters

allowUnreachableCode

Check for unreachable code

Optional values: true, ignoring unreachable codes false, unreachable codes cause errors

noEmitOnError

Do not compile if there are errors. Default: false

npm i -D less less-loader css-loader style-loader
Copy the code

Question:request to https://registry.cnpmjs.org/ts-loader failed, reason: Hostname/IP does not match certificate's altnames: Host: registry.cnpmjs.org. is not in the cert's altnames: DNS:r.cnpmjs.org

Run the following command:

Disable HTTPS for NPM (unauthenticate HTTPS for NPM)

npm config set strict-ssl false
Copy the code
npm ERR! code ERR_TLS_CERT_ALTNAME_INVALID
npm ERR! errno ERR_TLS_CERT_ALTNAME_INVALID
npm ERR! request to https://registry.cnpmjs.org/cnpm failed, reason: Hostname/IP does not match certificate's altnames: Host: registry.cnpmjs.org. is not in the cert's altnames: DNS:r.cnpmjs.org

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\41586\AppData\Roaming\npm-cache\_logs\2020-08-23T00_26_46_591Z-debug.log
Copy the code

Solutions:

npm config set registry http://registry.npmjs.org/
Copy the code

Using TypeScript + Webpack + Less project dependencies:

TypeScript: TypeScript. Ts - loader; Webpack: Webpack; Webpack - cli; Webpack dev - server; HTML - webpack - plugin; The clean - webpack - plugin; Babel: core - js. Babel - loader; @ Babel/core; @ Babel/preset - env. Less & CSS resources: style-loader; CSS - loader; Less; Less - loader; Postcss; Postcss - loader; Postcss preset - env.Copy the code

Execute the following commands to install the dependencies and compile the project, respectively:

# install depends on NPM I # build package NPM run buildCopy the code

Use NPM run start to enter development mode.

Question:

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. - configuration.output has an unknown property 'environment'. These properties are valid: object { auxiliaryComment? , chunkCallbackName? , chunkFilename? , chunkLoadTimeout? , crossOriginLoading? , devtoolFallbackModuleFilen ameTemplate? , devtoolLineToLine? , devtoolModuleFilenameTemplate? , devtoolNamespace? , filename? , futureEmitAssets? , globalObject? , has hDigest? , hashDigestLength? , hashFunction? , hashSalt? , hotUpdateChunkFilename? , hotUpdateFunction? , hotUpdateMainFilename? , jsonpFunc tion? , jsonpScriptType? , library? , libraryExport? , libraryTarget? , path? , pathinfo? , publicPath? , sourceMapFilename? , sourcePrefix? , strictModuleExceptionHandling? , umdNamedDefine? , webassemblyModuleFilename? } -> Options affecting the output of the compilation. `output` options tell webpack how to write the compiled files to disk.Copy the code
npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] build: 'webpack' NPM ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] build script.npm ERR! This is probably not a problem with npm. There is likely additional logging output above.Copy the code

Mode Mode (Mode)

Provides the mode configuration option to tell WebPack to use the built-in optimizations for the corresponding mode.

Providing the mode configuration option tells webpack to use its built-in optimizations accordingly.

string = 'production': 'none' | 'development' | 'production'
Copy the code

usage

Simply provide the mode option in the configuration object:

module.exports = {
  mode: 'development',
};
Copy the code

Or from the CLI parameter:

webpack --mode=development
Copy the code

Mode: development

// webpack.development.config.js
module.exports = {
 mode: 'development'
Copy the code

Mode: production

// webpack.production.config.js
module.exports = {
  mode: 'production',
Copy the code

Mode: none

// webpack.custom.config.js
module.exports = {
 mode: 'none',
Copy the code

If you want to change the packaging behavior based on the mode variable in webpack.config.js, you must export the configuration as a function rather than an exported object:

var config = {
  entry: './app.js',
  //...
};

module.exports = (env, argv) => {
  if (argv.mode === 'development') {
    config.devtool = 'source-map';
  }

  if (argv.mode === 'production') {
    //...
  }

  return config;
};
Copy the code

css

// Clear the default style * {margin: 0; padding: 0; Box-sizing: border-box; // Box-sizing: border-box; }Copy the code

The box-sizing property is used to change the default CSS box model used to calculate the width and height of elements. You can use this property to simulate browser behavior that does not support the CSS box model specification correctly.

Basic specification of box properties:

  1. Width and height Set the width and height of the content box. The content box is the area where the content of the box is displayed, including the text content in the box.

  2. Padding represents a CSS box padding layer between the outer edge of the content box and the inner edge of the border.

  3. The border of the CSS box is a separator layer.

  4. Margin is the outer area around the CSS box.

  • box-sizing:border-boxattribute

Box-sizing :border-box

width=content+padding+border

Flex layout is used. For self-adaptation, width is %, border, padding and margin are PX. Box-sizing :border-box is used for all outer boxes to change the structure of the box.

Background clip property

  • background-clip: border-boxThe background is cropped to the border box

#div {
    padding: 25px;
    border:10px dotted #000;
    background-color: yellow;
    background-clip: border-box;
}
Copy the code
  • background-cilp: padding-box;The background is clipped to the inside margin box;

#div {
    padding: 25px;
    border:10px dotted #000;
    background-color: yellow;
    background-clip: padding-box;
}
Copy the code
  • background-clip: content-box;The background is cropped to the content box.

#div {
    padding: 25px;
    border:10px dotted #000;
    background-color: yellow;
    background-clip: content-box;
}
Copy the code

Block-level boxes and inline boxes

  • Block-level box

A box defined at the block level behaves as follows:

  • The box expands in an inline direction and takes up all the space available to the parent container in that direction, which in most cases means that the box is as wide as the parent container

  • Each box will wrap

  • The width and height attributes come into play

  • Padding, margin, and border “push” other elements away from the current box

  • Inline boxes

An inline box defined to behave as follows:

  • Boxes do not generate line breaks.
  • Width and heightAttributes will have no effect.
  • Vertical margins, margins, and borders are applied but do not place the rest ininlineStatus box pushed open.
  • Horizontal margins, margins, and borders will be applied and will put others ininlineStatus box pushed open.

To form a block-level box in CSS, you need:

Content Box: This area is used to display Content, which can be sized by setting width and height.

Padding box: The empty area surrounding the content area; The size is set using the padding property.

Border box: Border box wraps content and inner margins. The size is set by the border attribute.

Margin box: This is the outermost area, the empty space between the box and other elements. The size is set by the margin attribute.

In the standard model, if you set width and height for a box, you actually set the content box.

The padding and border, together with the width and height set, determine the size of the box.

Example:

.box {
  width: 350px;
  height: 150px;
  margin: 25px;
  padding: 25px;
  border: 5px solid black;
}
Copy the code

If you use standard model width = 410px (350 + 25 + 25 + 5 + 5), height = 210px (150 + 25 + 25 + 5 + 5), padding + border + Content box.

Alternative (IE) box model

The default browser uses the standard model. If you need to use an alternative model, you can do so by setting box-sizing: border-box for it.

Example:

.box {
  box-sizing: border-box;
} 
Copy the code

Go back to my previous articles and you may get more!

  • A qualified junior front-end engineer needs to master module notes
  • More than 234.77 million words in front-end simulation interview
  • Vue.js pen test questions Solve common business problems
  • [Primary] Personally share notes of Vue front-end development tutorial
  • A long summary of JavaScript to consolidate the front end foundation
  • ES6 comprehensive summary
  • Dada front-end personal Web share 92 JavaScript interview questions with additional answers
  • [Illustrated, like collection oh!] Re-study to reinforce your Vuejs knowledge
  • 【 Mind Mapping 】 Front-end development – consolidate your JavaScript knowledge
  • 14 – even liver 7 nights, summed up the computer network knowledge point! (66 items in total)
  • This was my first JavaScript primer
  • LocalStorage and sessionStorage localStorage
  • Drag and drop in HTML5
  • Challenge the front-end HTTP/ECMAScript
  • Must learn must learn – Audio and video
  • 170 Interview questions + answer Learn to organize (conscience making)
  • Front-end HTML5 interviewers and candidates ask and answer questions
  • Ne Zha is sweeping the sea
  • Tencent location service development applications
  • [Advanced] The interviewer asked me how Chrome renders (6000 words)
  • The interviewer started by asking me about Chrome’s underlying principles and HTTP protocol (swastika)
  • Staying up late summed up the “HTML5 Canvas”
  • This /call/apply/bind
  • The HTTP/HTTPS/HTTP2 / DNS/TCP/classic problem
  • Execute context/scope chain/closure/first-class citizen
  • Web page creation basics
  • Learn the summary of HTML5 finger front-end (suggested collection, illustrated)

❤️ follow + like + Favorite + comment + forward ❤️

Likes, favorites and comments

I’m Jeskson, thanks for your talent: likes, favorites and comments, and we’ll see you next time! ☞ Thank you for learning with me.

See you next time!

This article is constantly updated. You can search “Programmer Doraemon” on wechat to read it for the first time, and reply [information] there are materials of first-line big factories prepared by me, which have been included in this article www.dadaqianduan.cn/#/

Star: github.com/webVueBlog/…