Front-end interview questions (3)--CSS

Knowledge points:

1、import

The import command is used to import CSS styles; Link tags can import external CSS styles, and import can still import external styles;

The basic usage of import:

1) Import external styles in the HTML file:

<style>
    @import url('./index.css')
</style>

To directly use @import to import external CSS files in the HTML source code, you need to put @import into the style tag

2) Introduce another CSS file in the CSS file

@import url('./index.css')
(后面书写其他样式)

3) The @import rule also supports media queries, so it can allow media-dependent imports

@import "printstyle.css" print;
只在媒体为print时导入“printstyle.css”样式表

@import "mobstyle.css" screen and (max-width:768px)
只在媒体为screen且视口最大宽度768像素时导入“mobstyle.css”样式表

The difference between import and link:

1) Link is an HTML tag, and @import is completely provided by CSS ; besides loading CSS, link tags can also do many other things, such as defining RSS, defining rel connection attributes, etc., @import can only load CSSl

2) The difference in loading order : For example, if you use import to refer to b.css in a.css, the browser will know that there is another b.css only after the host css file a.css using the import command is downloaded and parsed. The css needs to be downloaded, so it is downloaded at this time, and then a series of operations such as parsing and building a render tree start after downloading;

3) Compatibility difference : Since @import is proposed by CSS2.1, old browsers do not support it. @import can only be recognized by IE5 and above, but the link tag does not have this problem

4) When using JS to control the DOM to change the style, only the link tag can be used, because @import is not controllable by the DOM; for a skinnable website, it can be changed by changing the two href values ​​​​of the link tag Apply an unused external style sheet, but it cannot be operated on import, after all, it is not a label;

In addition, from the perspective of performance optimization, try to avoid using @import; using @import to introduce CSS will affect the parallel download of the browser, and the CSS file referenced by @import can only be downloaded and parsed after the CSS file that references it is downloaded and parsed , the browser will know that there is another CSS that needs to be downloaded, and then it will download it, and then start parsing after downloading to build a render tree;

Multiple @imports will cause the download order to be out of order. In IE, @import will cause the download order of resource files to be disrupted, that is, the JS files arranged after @import are downloaded before @import, and disrupt or even destroy the parallel download of @import itself.

2. The calc function of CSS3

Calc is the abbreviation of the English word calculate (calculation), which is a new function of CSS3; MDN explains that it can be used in any length, value, time, angle

Frequency, etc., the syntax is as follows:

width:calc(100% - 80px)

Common +-*/ symbols can be used for calculations, but it should be noted that +- must be separated by spaces. The reason is very simple. If the - sign and the calculated number are close together, the browser will consider it when parsing This may be a negative value.

Vertical centering using computed properties combined with absolute positioning:

父元素:
position:relative;

子元素:
position:absolute;
top:calc(50% - 自身高度的一半)
left:calc(50% - 自身高度的一半)

3. CSS3 Media Queries

The full English name of Media Query is Media Query. As the name suggests, it will query the media used by users. Nowadays, there are many browser terminals for web pages, and users can browse web pages through different terminals, such as PC, mobile TV, etc. Although we cannot guarantee that a website looks exactly the same on different screen sizes and different devices, at least we must make our web pages adapt to the user's terminal. The Media Query (media query) module in CSS3 is used to adapt a page to different terminals.

Media types supported in CSS : Commonly used are all (all), screen (screen) and print (page printing or print preview mode).

Media type reference method :

1) link method: the link method to introduce media types is to specify different media types through the media attribute in the link tag when the link tag refers to the style, as follows:

<link rel="stylesheet" href="index.css" media="screen and (max-width:600px)"/>
<link rel="stylesheet" href="print.css" media="print"/>

2) XML method: The xml method is similar to the link method, and is also specified through the media attribute, as follows:

<? xml-stylesheet rel="stylesheet" media="screen" href="style.css" ?>

3) @import: There are two main ways for @import to introduce media types. One is to call another style file through @import in the CSS style sheet, and the other is to introduce it in the style tag. Note: IE6 and IE7 do not support this method.

Introduce the media type in the style file:

@import url('./index.css') screen

Introduce the media type in the style tag:

<style>
    @import url('./index.css') screen
</style>

4) The way of @media (commonly used) : @media is a new feature introduced in CSS3, called media query. There are also two ways for @media to introduce media, as follows:

Introduce the media type in the style file:

@media screen and (max-width:600px){
    具体样式
}

Introduce the media type in the style tag:

<style>
    @media screen{
        具体样式
    }
</style>

The specific formula :

@media 媒体类型 and (媒体特性){
    具体样式
}

For example:

@media screen and (min-width:480px) and (max-width:900px){
    具体样式
}

Note :

1) not keyword: used to exclude a specific media type and media characteristics

@media not print and (max-width:480px){
    具体样式
}

The style code will be used on all devices except printing devices and screen widths less than or equal to 480px.

2) Unspecified Media Type: If the Media Type is not explicitly specified in the media query, the default value is all

@media (max-width:900px){
    具体样式
}

The above style applies to all devices with screen size less than or equal to 900px.

4. CSS3 transitions and animations

Transition: refers to the state when the attribute of the element changes

div{
    width:100px;
    transition:all 1s;
}
div:hover{
    width:200px
}

The above example means that all attributes in the div will undergo a 1-second transition when they change;

transition is a compound property:

transition-property: Specify the CSS property for the transition; none: No property will get the transition effect; all: All properties will get the transition effect; property: Define the list of CSS property names that apply the transition effect, and the list is separated by commas. Not all attributes can be transitioned, and only attributes with a midpoint value can perform transition effects.

transition-duration: Specifies the time required for the transition to complete;

transition-timing-function: Specify the transition function; this attribute is used to set the speed of the transition;

transition-delay: Specifies the delay time of the transition; how long the transition delay is triggered, in seconds or milliseconds, but the value can be positive integers, negative integers and 0.

If there are multiple element transitions, just separate them with commas:

transition:background-color 2s,height 5s

transition event

Sometimes, some content will be executed after the transition effect is over, and there is a corresponding transitionend event, which is convenient for us to monitor whether the transition effect is over, for example:

<div id="oDiv"></div>

div{
    width:100px;
    height:100px;
    background-color:skyblue;
    transition:all 3s
}
var div = document.getElementById("oDiv");
div.onclick = function(){
    div.style.height = "400px"
}
div.ontransitionend = function(){
    console.log("过渡结束后触发")
}

Animations in CSS3:

Animation using CSS3 animation consists of two parts: the first is to declare an animation with keyframes, and the second is to call the animation declared by keyframes in animation.

Syntax for declaring animations : @keyframes animationname {keyframes-selector {css-styles;}}

animationname: required, defines the name of the animation;

keyframes-selectior: required, the percentage of animation duration, legal value: 0-100%;

css-styles: Required, one or more valid styles.

Using animation : calling animation through animation property in CSS3

animation:name (the keyframe name of the selector to be bound) duration (specify how many seconds to complete) timing-function (how to complete a cycle) delay (set the delay interval before the animation starts) iteration-count (defining the playback of the animation times) direction (specifies whether the animation should be played in reverse in turn) fill-mode (specifies the style to be applied to the element when the animation is not playing) play-state (specifies whether the animation is running or paused)

Animation corresponding event:

animationstart : Triggered after the css animation starts;

animationiteration: Triggered when the css animation is played repeatedly;

animationend: triggered after the animation is completed

5. Progressive enhancement and graceful degradation

Progressive enhancement, the English full name is progressive enhancement, which refers to building pages for low-version browsers to ensure the most basic functions, and then improving and adding functions for advanced browsers to achieve better user experience;

Graceful degradation, the English full name is graceful degradation, which builds complete functions from the beginning, and then makes compatibility for lower version browsers.

These two concepts are "upward compatibility" and "downward compatibility". Progressive enhancement is equivalent to upward compatibility, and graceful degradation is equivalent to downward compatibility. Backward compatibility means that higher version browsers support lower versions, or that later developed versions are compatible with earlier developed versions.

Under the premise of determining the user group, progressive enhancement: build pages for low-version browsers to ensure basic functions, and then improve and add functions such as effects and interactions for advanced browsers to achieve a better user experience; graceful degradation: one Build complete functionality from the start, and then make it compatible with lower version browsers.

Difference: Graceful degradation starts from the complex status quo and tries to reduce the supply of user experience, while progressive enhancement starts from a basic, functional version and then expands to meet the needs of future environments.

For example, look at the writing order of the following two pieces of code. It seems that the writing order is different, but it actually shows the focus of our development:

渐进增强写法:
transition{
    -webkit-transition:all 5s;
    -moz-transition:all 5s;
    -o-transition:all 5s;
    transition:all 5s;
}
优雅降级写法:
transition{
    transition:all 5s;
    -o-transition:all 5s;
    -moz-transition:all 5s;
    -webkit-transition:all 5s;
}

The browser support for prefix CSS3 (-webkit-, -moz-, -o-) and normal CSS3 is as follows:

1) A long time ago: browser prefix CSS3 and normal CSS3 are not supported;

2) Not long ago: browsers only supported prefixed CSS3, not normal CSS3;

3) Now: the browser supports both prefix CSS3 and normal CSS3;

4) Future: Browsers do not support prefixed CSS3, only normal CSS3.

The vast majority of large companies adopt the progressive enhancement method, because the salesman is given priority, and improving the user experience will never be at the top.

6. CSS deformation

The transformation function provided for us in CSS3 :

1) Functions with X/Y: translateX, translateY, sclaeX, scaleY, skewX, skewY

2) 2D deformation functions: translate, sclae, rotate, skew, matrix

3) 3D deformation functions: rotateX, rotateY, rotate3d, translateZ, translate3d, scale3d, scaleZ, matrix3d

Transform property in CSS3 :

1) transform: deformation attribute;

2) transform-orign: the position of the center point of the deformation;

3) transform-style: is an important attribute of 3D space, which specifies how nested elements are presented in 3D space; flat: all sub-elements are presented in 2D space; preserve-3d: indicates that left and right sub-elements are presented in 3D space .

4) Perspective: It is used to set the position of the viewer, which can map the visual content to a viewing cone, and then cast it to a 2D viewing plane. If this property is not specified, all points in the Z-axis space will be tiled into the same 2D viewing plane, and there will be no concept of depth in the transformation result. A simple understanding is the viewing distance, which is used to set the distance between the user and the Z plane of the 3D space of the element. The effect is determined by its value. The smaller the value, the closer the user is to the Z-plane in 3D space, and the more impressive the visual effect; conversely, the larger the value, the farther the distance between the user and the Z-plane of 3D space, and the more impressive the visual effect. Just very small.

5) perspective-orign: the viewing position of the viewer

6) backface-visibility attribute: determines whether the backface of the element rotation is visible.

2D deformation :

Displacement: transform:translate(-50%,-50%)

scaling: sclae

Rotation: rotate

Tilt: skew

3D deformation:

Displacement: translate3d(tx,ty,tz)

Rotation: rotate3d(x, y, z, a); x, y, z can be a value between 0-1, which is the vector in the direction of the rotation axis; a represents the rotation angle, a positive value represents clockwise rotation, and a negative value Indicates counterclockwise rotation;

Zoom: scale(sx,sy,sz)

7. Progressive rendering

Progressive rendering, English full name progressive rendering, also known as lazy rendering, refers to the technology of presenting pages as quickly as possible in order to improve the loading speed perceived by users. Progressive rendering does not refer to a certain technology, but a collection of various technologies. For example: skeleton screen, lazy loading of images, image placeholders, splitting web resources

8. CSS rendering performance optimization

Significance of performance optimization: From the perspective of users: website optimization can make pages load faster and respond more timely, greatly improving user experience; from the perspective of service providers: optimization will reduce the number of page resource requests and the bandwidth occupied by requested resources, thereby saving Considerable bandwidth resources.

Optimization method :

1) Use the id selector

2) Avoid deep code

3) Don't use attribute selectors 

4) Usually put browser prefixes first and standard style properties last (progressive enhancement)

5) Comply with CSSLint rules

6) Don't use @import

7) Avoid excessive rearrangement (Reflow): Reflow means that the browser recalculates the layout position and size

8) Dependency inheritance

9. Cascading context

There are 3 ways to create a cascading context :

1) The root element HTML in HTML itself has a stacking context, which is called "root stacking context";

2) For ordinary elements, set the position attribute to a non-static value and set the z-index attribute to a specific value, which will generate a cascading context;

3) New properties in CSS3 can also generate cascading context

Cascading level and cascading order:

Both mean the display order of elements on the z-axis in the same stacking context; it's just that the former is a concept, and the latter is a specific rule.

Summarize:

1) First check whether the two elements to be compared are in the same stacking context:

If yes, whose cascading level is larger and who is on top;

If the two elements are not in the same stacking context, please compare the stacking registrations of the stacking contexts they are in first.

2) When two elements have the same stacking level and the same stacking order, the stacking level of the latter element in the DOM structure is above the previous element.

3) Stacking order: z-index is positive > z-index: auto/0 > inline/inline-block horizontal box > float box > block box > z-index is negative > stacking context

10. CSS3 masking

Application: Setting Reflections

-webkit-box-reflect:below 15px linear-gradient(transparent 10%,blue)

The first value is the position of the reflection (up above below below left left right right);

The second value is the reflection distance;

The third value is a mask: can be a linear gradient.

Interview questions:

1. What are the methods of CSS reference? What is the difference between link and @import?

CSS references are:

1) External links, external link style sheets through link tags

2) Inline, use the style tag to define the style in the head tag

3) Embed, define the style through the style attribute in the start tag of the element

The difference between link and @import:

1) Link is an HTML tag, and @import is completely provided by CSS ; besides loading CSS, link tags can also do many other things, such as defining RSS, defining rel connection attributes, etc., @import can only load CSSl

2) The difference in loading order : For example, if you use import to refer to b.css in a.css, the browser will know that there is another b.css only after the host css file a.css using the import command is downloaded and parsed. The css needs to be downloaded, so it is downloaded at this time, and then a series of operations such as parsing and building a render tree start after downloading;

3) Compatibility difference : Since @import is proposed by CSS2.1, old browsers do not support it. @import can only be recognized by IE5 and above, but the link tag does not have this problem

4) When using JS to control the DOM to change the style, only the link tag can be used, because @import is not controllable by the DOM; for a skinnable website, it can be changed by changing the two href values ​​​​of the link tag Apply an unused external style sheet, but it cannot be operated on import, after all, it is not a label.

2. Do you know the calculated properties of CSS?

That is, the calc() function is mainly used to specify the length of an element, and supports all CSS length units. A space needs to be reserved before and after the operator; for example: width: calc(100% - 50px)

3. How to use media query to realize that the div element width becomes 30% when the viewport width is greater than 320px and less than 640px

@media screen and (min-width:320px) and (max-width:640px){
    div{
        width:30%;
    }
}

4. What are the attributes of transition and animation in CSS3?

transition transition animation :

transition-property: Specify the CSS property of the transition;

transition-duration: specifies the time required for the transition to complete;

transition-timing-function: specify the transition function;

transition-delay: Specifies the transition delay time

animation keyframe animation :

animation-name: Specifies the name of the keyframe to be bound to the selector;

animation-duration: the animation specifies how many seconds it takes to complete;

animation-timing-function: set how the animation will complete a cycle;

animation-delay: Set the delay interval before the animation starts;

animation-iteration-count: defines the number of times the animation is played;

animation-direction: specifies whether the animation should be played in reverse in turn;

animation-fill-mode: specifies the style to be applied to the element when the animation is not playing;

animation-play-state: Specifies whether the animation is running or paused

5. How to implement CSS animation?

That is, the animation attribute, which controls the change of one or more attributes of the element, and can set multiple keyframes. Properties include the animation's name, completion time, period, interval, number of times to play, whether to play repeatedly, styles to apply when not playing, and whether the animation is paused or running. It can change the style of elements over time without triggering any events.

Animate with CSS :

1) @keyframes specifies the animation;

2) The shorthand property of all animation properties of animation;

3) animation-name specifies the name of the @keyframes animation;

4) animation-duration specifies the time seconds or milliseconds it takes for the animation to complete a cycle, and the default is 0;

5) animation-timing-function specifies the speed curve of the animation, the default is ease;

6) animation-fill-mode specifies the style to be applied to the element when the animation is not playing;

7) animation-delay specifies when the animation starts, the default is 0;

8) animation-iteration-count specifies the number of times the animation is played, and the default is 1;

9) animation-direction specifies whether to play the animation in reverse in the next cycle, the default is normal;

10) animation-play-state specifies whether the animation is running or paused, the default is running.

6. Talk about progressive enhancement and graceful degradation?

Progressive enhancement, the English full name progressive enhancement, refers to building pages for low-version browsers to ensure the most basic functions, and then improving and adding functions for advanced browsers to achieve better user experience;

Graceful degradation, the English full name is graceful degradation, which builds complete functions from the beginning, and then makes compatibility for lower version browsers.

7. Please briefly describe how to use the new deformation in CSS3?

The deformation in CSS3 is divided into 2D deformation and 3D deformation; the whole can be divided into three categories:

Functions with X/Y: translateX, translateY, sclaeX, scaleY, skewX, skewY

2D deformation functions: translate, sclae, rotate, skew, matrix

3D deformation functions: rotateX, rotateY, rotate3d, translateZ, translate3d, scaleZ, scale3d, matrix3d.

8. What is progressive rendering?

Progressive rendering, the English name progressive rendering, also known as lazy rendering, refers to the technology of presenting pages as quickly as possible in order to improve the loading speed perceived by users. But this is not a specific reference to a certain technology, but a collection of a series of technologies. For example: skeleton screen, image lazy loading, image placeholder, resource splitting.

9. Summarize how to improve or optimize CSS rendering performance?

The optimization of CSS rendering performance comes from all aspects, here are some common ways:

1) Using id selector is very efficient, because id is unique;

2) Avoid deep selector nesting;

3) Try to avoid using attribute selectors, because the matching speed is slow;

4) Use a progressive enhancement scheme;

5) Comply with CSSLint rules;

6) Do not use @import;

7) Avoid excessive rearrangement;

8) Rely on inheritance;

9) value abbreviation;

10) Avoid properties that consume performance;

11) The background image is optimized and merged;

12) File compression.

10. Please briefly describe what is a cascading context, what is a cascading level, and what is a cascading order?

Stacking context concept : In the CSS2.1 specification, the position of each box model is three-dimensional, which are the X axis, Y axis on the flat canvas and the Z axis representing the stack. In general, elements are tiled along the X-axis and Y-axis on the page, and we cannot perceive their cascading relationship on the Z-axis. And once the elements are stacked, it can be found that an element may cover another element or be covered by another element.

Cascading context trigger conditions :

1) The root element in HTML HTML itself has a stacking context, called "root stacking context"

2) Ordinary elements set the position attribute to a non-static value and set the z-index attribute to a specific value to generate a cascading context

3) New properties in CSS3 can also generate cascading context

Cascade level:

If two elements are in the same stacking context, the element with a higher stacking level will be at the front. The cascading level is a concept, and the size of the cascading level can be judged according to the cascading sequence.

Stacking order :

The stacking order means that when elements are stacked, they are displayed vertically on the Z axis according to specific sequence rules. To put it simply, it is how to judge the stacking when the elements are in the same stacking context: z-index is positive > z-index: auto/0 > inline/inline-block horizontal box > float box > block box > z-index is negative > Cascading contexts. 

11. Redrawing and rearranging

When the modification of the DOM results in a style change and does not affect the geometric properties, it will cause redrawing;

When our modification of the DOM structure causes a change in the geometric size of the DOM, a reshooting process will occur. For example: the geometric properties of a DOM element change. Common geometric properties include width, height, padding, margin, left, top, border etc.; when the DOM node increases or decreases, and when reading and writing offset, scroll, and client attributes, the browser needs to perform a rearrangement operation in order to obtain these values, and call the window.getComputedStyle method;

Rearrangement process: According to the rendering pipeline, when reordering is triggered, if the DOM structure changes, the DOM will be re-rendered, and then the rendering process will go through again.

Summary: redrawing does not necessarily lead to rearrangement, rearrangement must lead to redrawing.

12. New features of css3:

border-color: set multiple colors for the border;

border-radius: rounded border;

box-shadow: shadow effect;

background-size: specify the size of the background image;

text-shadow: text shadow

Guess you like

Origin blog.csdn.net/qinqinzqq/article/details/128976282