link
vs @import
- Link belongs to the XHTML tag, while
@import
CSS provides this. - When the page is loaded, link is loaded at the same time, and
@import
Referenced CSS will wait until the page is loaded. - Import is only recognized in IE 5 or higher, while link is an XHTML tag with no compatibility issues.
- Link mode has a higher style weight than
@import
The weight. - Differences when using DOM to control styles. When using javascript to control the DOM to change styles, you can only use the link tag because
@import
It’s not dom control.
CSS Hardware Acceleration
CSS hardware acceleration refers to handing over the browser’s rendering process to the GPU, rather than using its own slower renderer, which makes animation and transition smoother
To turn on hardware acceleration, use a specific CSS statement:
/** Use 3d effects to enable hardware acceleration **/
.speed-up {
-webkit-transform: translate3d(250px.250px.250px) rotate3d(250px.250px.250px, -120deg) scale3d(0.5.0.5.0.5);
}
Copy the code
If you don’t need to use the transform and just turn on hardware acceleration, you can write:
/** In principle, hardware acceleration is enabled using 3d effects **/
.speed-up {
-webkit-transform: translateZ(0);
-moz-transform: translateZ(0);
-ms-transform: translateZ(0);
-o-transform: translateZ(0);
transform: translateZ(0);
}
Copy the code
For Safari and Chrome, there may be flickering problems with animation or Transition. You can use this method to resolve the problem:
.speed-up {
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-perspective: 1000;
-moz-perspective: 1000;
-ms-perspective: 1000;
perspective: 1000;
/** WebKit can also use the following statement **/
-webkit-transform: translate3d(0.0.0);
-moz-transform: translate3d(0.0.0);
-ms-transform: translate3d(0.0.0);
transform: translate3d(0.0.0);
}
Copy the code
Note: Hardware acceleration is best used only on animation or Transform. Don’t abuse hardware acceleration, as this can add to performance, and if you abuse it, it will make the animation more sluggish, which is not worth the cost.
Mobile 1px problem
Mobile devices have one parameter: devicePixelRatio (DPR), which is the ratio of device pixels to CSS pixels when the default zoom is 100%.
window.devicePixelRatio = 'Physical pixel /CSS pixel'
Copy the code
The current mainstream screen DRP is either 2(Iphone 8) or 3(Iphone 8 Plus).
The solution
1. WWDC’s solution for IOS: Reduce the value
border:0.5 px. solid #E5E5E5
Copy the code
- Advantages: Simple, no side effects
- Cons: supports IOS8+
2. Use border images
border: 1px solid transparent;
border-image: url('. /.. /.. /image/96.jpg') 2 repeat;
Copy the code
- Advantages: No side effects
- Disadvantages: Not flexible enough, poor performance
3. Use the box – shadow
box-shadow: 0 -1px 1px -1px #e5e5e5// Top edge1px 0 1px -1px #e5e5e5// The right line0 1px 1px -1px #e5e5e5, // lower sideline -1px 0 1px -1px #e5e5e5; / / the left lineCopy the code
4. Use pseudo-elements
- A border
.setOnePx{
position: relative;
&::after{
position: absolute;
content: ' ';
background-color: #e5e5e5;
display: block;
width: 100%;
height: 1px; /*no*/
transform: scale(1.0.5);
top: 0;
left: 0; }}Copy the code
- Article 4 the border:
.setBorderAll{
position: relative;
&:after{
content:"";
position:absolute;
top: 0;
left: 0;
width: 200%;
height: 200%;
transform: scale(0.5);
transform-origin: left top;
box-sizing: border-box;
border: 1px solid #E5E5E5;
border-radius: 4px; }}Copy the code
- Advantages: Good compatibility
- Cons: Style influences need to be considered
5. Set the viewport scale
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" id="WebViewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<script>
var viewport = document.querySelector("meta[name=viewport]");
// Set the viewPort according to the device pixel
if (window.devicePixelRatio == 1) {
viewport.setAttribute('content'.'width=device-width,initial-scale=1,maximum-scale=1, minimum-scale=1, user-scalable=no');
}
if (window.devicePixelRatio == 2) {
viewport.setAttribute('content'.'width = device - width, initial - scale = 0.5, the maximum - scale = 0.5, the minimum - scale = 0.5, user - scalable = no');
}
if (window.devicePixelRatio == 3) {
viewport.setAttribute('content'.'width = device - width, initial - scale = 03333333333333333, maximum - scale = 0.3333333333333333, the minimum - scale = 03333333333333333, user-scalable=no');
}
var docEl = document.documentElement;
var fontsize = 32* (docEl.clientWidth / 750) + 'px';
docEl.style.fontSize = fontsize;
</script>
Copy the code
- Advantages: convenient, directly write 1px can be
- Disadvantages: Not applicable to the old project, the scope of influence is relatively large
What are the methods of CSS performance optimization?
- Merging CSS files, if the page loads 10 CSS files at 1K each, it is also slower than loading only one CSS file at 100K.
- Reduce CSS nesting, preferably not more than three layers.
- Do not nest in front of ID selectors; ids are unique and have high permissions; nesting is a waste of performance.
- Create a common style class that extracts the same style and uses it as a common class.
- Reduce the use of wildcard * or selectors like [hidden=”true”] and look for all… Will it work?
- Using CSS inheritance, if the parent node is defined, the child node does not need to be defined.
- Split out the common CSS file. For larger projects, you can extract most of the common structural styles of the page into a single CSS file, which will be cached after a single download. Of course, this will increase the number of requests.
- Instead of using CSS expressions, expressions just make your code look cool, but they can be more wasteful of performance than you might think.
- If you use CSS REST less, you might think that restyling is the norm, but there are a lot of things that are unnecessary and unfriendly. Normolize.css is a good choice if you’re interested.
- CssSprite, synthesize all icon images, display icon images in the way of width and height plus background-position, which is very practical and reduces HTTP requests.
- After that, CSS compression (YUI Compressor, an online compression tool) is optimized for file size
- GZIP compression, a popular file compression algorithm, further reduces network transmission load and improves load performance
- Avoid the use of
@import
, used in external CSS files@import
Can cause the page to add an additional delay when loading. - Avoid excessive rearrangement (backflow): The backflow of the browser consumes a large amount of computing resources
Conditions that cause reflow to occur:
- Resize the window
- Change the size of the text
- Add delete style sheets
- Change the content of the input box input content will also
- Activation of pseudo-classes
- Manipulating class attributes
- Scripts manipulate DOM JS to change CSS classes
- Calculate offsetWidth and offsetHeight
- Setting the style property
- Change the inner and outer margins of elements
Common reflux elements
- Related to the size of the width, height, padding, margins, border width, border, min – height
- About the display layout, the top position, float, left, right, bottom
- Font size,text-align,font-weight,font-family,line-height,white-space,vertical-align
- Hide related overflow,overflow-x,overflow-y
Recommendations for optimizing reflux
- Instead of styling the DOM one by one, pre-define the class and then modify the DOM classname
- Do not modify dom with a wide range of influence
- Use absolute positioning for animation elements
- Do not make a table layout, because a small change will cause the entire table to be rearranged
- Avoid setting a lot of style attributes. Changing the node style by setting the style attribute will trigger reflow every time, so use the class attribute instead
- If the CSS has a calculated expression, it is recalculated each time, triggering a reflow
Transition and animation
transition
Need to trigger, such as click event, mouse move event, and animation can cooperate@keyframe
It can be executed automaticallytransition
Trigger once play once, whileanimation
Can be set to modify the number of cycles, animation state and so on.transition
Look at changes in style properties, and the relationship between property values and time can be a cubic Bezier curve,animation
Scoped elements themselves rather than style attributes, using the concept of keyframes, allow for more free animation- In terms of performance: the browser has a main thread and a layout thread. The main thread is mainly responsible for JS running, page layout, bitmap generation and so on, and then passes the generated bitmap to the layout thread. The layout thread will draw the bitmap to the page through GPU, and also request the bitmap to the main thread. In the use of
animation
In the process, we may changewidth
.height
Changing the properties of the document flow can cause page backflow and redrawing, which can affect performance. whiletransition
Will combinetransform
To rotate and scale, creating a new layer without causing redraw and reflow.
What are the meanings and usages of calc, support and media?
The @Supprot function is mainly used to check whether the browser supports a CSS attribute. In essence, it is a conditional judgment. If it supports one attribute, apply one style, otherwise provide another style.
@supports (display: grid) {
div {
display: grid; }}@supports not (display: grid) {
div {
float: right; }}Copy the code
@Supports is accessible in JS through the CSS object interface model CSSSupportsRule.
Calc () is used to dynamically calculate the length value, supporting the conventional four operations /
@media, for media queries to apply different styles.
Advantages and disadvantages of image Base64 encoding
Advantages:
- Reduce HTTP requests for an image
Disadvantages:
- According to the principle of Base64 encoding, the encoded file size will be 1/3 larger than the source file, if the large image is encoded to
html/css
, which increases the file size, affects the file loading speed, and increases the time for the browser to parse HTML and CSS - Basr64 does not cache images directly
- Browsers prior to IE8 do not support it
Layout ViewPort, Visual ViewPort and Ideal ViewPort?
There are three viewports to understand on mobile:
- Layout viewport (
layout viewport
), when displaying the web page on the mobile terminal, due to the small screen size of the mobile terminal, if the web page is laid out using the screen size of the mobile terminal, the whole page will be displayed incorrectly. So mobile browsers provide onelayout viewport
The layout viewport concept, using this viewport to display the page, generallylayout viewport
The size of the page is 980px, so the layout of the page doesn’t change much, and we can view the page by dragging and zooming - Visual port (
visual viewport
), visual viewport refers to the viewport size of the area we can see, generally the resolution of the screen. The relationship between visual viewport and layout viewport: visual viewport is like a window, and layout viewport is the scenery outside the window. - Ideal viewport (
ideal viewport
), ideal viewport due tolayout viewport
General thanvisual viewport
Large, so you have to drag the page to see the entire page. Hence the concept of the ideal viewport,ideal viewport
Users can see the entire page with different zooming and scrolling bars, and the size of content displayed on the page is the same at different resolutions.ideal viewport
It’s just by modifying itlayout viewport
Let the size of the device be large equal to the width of the device, which can be understood as device-independent pixels. So a page designed for an ideal viewport should look the same at different resolutions.
The Settings are as follows:
< metaname = "viewport" content = "width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, the minimum - sca Le = 1.0, user - scalable = no "/ >Copy the code
Overflow: How to handle the problem that scrolling cannot be smooth?
{
-webkit-overflow-scrolling:touch; // Enable hardware acceleration}Copy the code
How does the browser determine whether webP images are supported
- Width and height judgment method. Create an image object, set its SRC property to a WebP image, and then get the width and height of the image in the onLoad event, as shown in figure 2
If it can be obtained, the browser supports WebP images. If the onError function cannot be retrieved or raised, the browser does not support WebP grid images.
- Canvas judgment method. We can dynamically create a Canvas object, set it to WebP format via the Canvas toDataURL, and decide
Whether the returned value contains the image/webp field. If the value contains the image/ webP field, webP is supported; otherwise, webP is not supported.
What is a replacement element
An element that can be replaced by changing the value of an attribute is called a “replacement element.” Thus, ,
In addition to the property that content is replaceable, replacement elements have the following properties.
- The appearance of the content is not affected by CSS on the page. In technical terms, styles are rendered outside the scope of CSS. How do I change the appearance requirements of the replacement element itself
Like the appearance attribute, or some style interface exposed by the browser itself,
- It has its own size. On the Web, the default size (excluding borders) for many replacement elements without an explicit size is 300 pixels by 150 images
Elements, such as
- It has its own set of presentation rules for many CSS properties. Typical is the vertical-align attribute, ve for replacement and non-replacement elements
The value of the rtical-align attribute is interpreted differently. For example, the default baseline of vertical-align is defined as the lower edge of the character X, while the baseline of the replacement element is defined as the lower edge of the element.
- All replacement elements are inline horizontal elements, that is, replacement elements and replacement elements, replacement elements and text can be displayed on a single line. However, replace elements by default
The display values are inline and inline-block.
Will background-image of hidden elements load?
-
Background image of element:
- Element Settings
display:none
, will request an image, - Parent element Settings
display:none
Will not request images - Styles are not used by elements and are not requested
:hover
Style, when triggered request
- Element Settings
-
Img tag image: Images are requested in any case
Img/background
- From the perspective of parsing mechanism:
- According to the browser’s parsing mechanism, HTML tags are parsed first.
- If you just show an image, for example
banner
Advertising image, can be usedbackground
, the unimportant items are automatically lined to the back to avoid occupying bandwidth and causing data congestion - When images are large and not lazy-loaded, background is a better choice
- The nice thing about the IMG tag is that it closes itself and avoids empty notes
- From SEO:
- Img is a self-closing label and cannot be added with text. It can be set
alt
Properties. - The advantages are: screen reader friendly; Disadvantages: need to set the display interval
- Img is a self-closing label and cannot be added with text. It can be set
- From the perspective of semantics:
- Img is a semantic tag
Implement a width and height adaptive square
/*1. The first way is to use VW to implement */
.square {
width: 10%;
height: 10vw;
background: tomato;
}
/*2. The second method uses the fact that the margin/padding percentage of the element is relative to the parent element width to implement */
.square {
width: 20%; /* 20% of the width of the parent element */
height: 0;
padding-top: 20%; /* 20% of the width of the parent element */
background: orange;
}
/*3. The third way is to use the child element's margin-top value to implement */
.square {
width: 30%;
overflow: hidden;
background: yellow;
}
.square::after {
content: ' ';
display: block;
margin-top: 100%;
}
Copy the code
What is the calculation baseline when different properties in the CSS are set to %?
Formula: The CSS attribute value of the current element = base * the percentage
- When the position of the element is relative and absolute, the top and bottom, left and right benchmarks are the height and width of the block, respectively
- When position is fixed, top and bottom, left and right benchmarks are the height and width of the initial block (i.e. viewport) respectively. For more complex mobile devices, the benchmarks are the height and width of the Layout Viewport
- When the height and width of an element are set to percentages, the base is the height and width of the containing block, respectively
*
When margin and padding are set to percentages, the base is the width containing the block (error-prone)- The border-width of the element does not support percentages
- The text-indent of the element, based on the width of the containing block
- Border-radius of the element, based on its height and width, respectively
- The background-size of the element is its height and width, respectively
- The translateX and translateY of the element are their height and width respectively
- The element’s line-height is based on its own font size
- The font size of the element, based on the parent element font
Refer to the link
- CSS style priority
- Enable CSS3 hardware acceleration
- CSS performance optimization
- CSS is often tested on interview questions