Summary of recommendations and performance optimizations for CSS

Source: Internet
Author: User

1. Preface

There are a few days to the national Day mid-Autumn Festival, is about to leave, first wish everyone happy holiday! Before writing the JS writing tips and tricks, then today to talk about CSS it! When it comes to CSS, each page is inseparable from CSS, but for CSS, many developers think that CSS can be used as long as the layout, the platoon out on it, other details or optimization, do not need to consider. But I think the CSS is not just the layout of the page is finished, but also need to consider a lot of details have been optimized, not like everyone thought so simple, in the study, if found any skills or optimization points, I will also apply to the use of! So today, share my summary of CSS writing suggestions and performance optimization of some problems! Hope to help everyone to the magic of the CSS have a new understanding, of course, if you think there are any other suggestions. Welcome advice!

2.CSS Rendering Rules

The first choice, about CSS rendering rules, you probably all know, is right-to-left rendering! Chestnuts as follows

. Nav h3 a{font-size:14px;}

The rendering process is probably: first Find all a , along a the parent element to find h3 , and then along h3 , find .nav . Join the result set by finding a node that matches the matching rule halfway. If no match is found for the root element, the html path is no longer traversed, and a the lookup match is repeated from the next start (as long as there are multiple right-most nodes on the page a ).
Reference: Right-to-left matching rules for CSS selectors

3. No more than 3 levels of nesting levels

In general, the nesting level of an element cannot exceed 3 levels, and excessive nesting can cause code to become bloated, redundant, and complex. Causes the CSS file volume to become big, causes the performance to waste, affects the rendering speed! And too dependent on the HTML document structure. Such CSS style, maintenance up, extremely troublesome, if you want to modify the style later, you may want to use !important overrides.

4. Style Reset

This I am currently neutral opinion, because look at the article online, some people support the use of style reset, some people do not support the use, who can not persuade who. My own situation, I have used the style reset, but is a relatively simple summary, the code is as follows!

Body,dl,dd,h1,h2,h3,h4,h5,h6,p,form,ol,ul {  margin:0;  padding:0;} H1, H2, H3, H4, H5, h6 {  font-weight:normal;} OL, ul {  list-style:none;} h1{  font-size:24px;} h2{  font-size:20px;} h3{  font-size:18px;} h4 {  font-size:16px;} h5{  font-size:14px;} h6{  font-size:12px;}

5. Style level

First, the CSS style level is organized as follows

!important> inline style >id style >class style > label name style.
Then one thing to mention is that the combined selector usage value will be superimposed. For example, the weight of the ID is 100,class is 10, the signature is 1 (other unclear)! So p.test-class the weight is one, and that p#test 's 101.

For example, there is a P

<p id= "test" class= "Test-class" style= "Color:green;" ></p>

So the style weights are

p {color:red!improtant;} (Greater than everything below) <p id= "test" class= "Test-class" style= "color:black;" ></p> (Greater 111) P#test.test-class (111) #id. Test-class (+) P#test (101) # Test (+) P.test-class (one). Test-class (1) * (less than 1)

Margin of 6.inline-block

Don't explain, look at the picture

The above p elements margin padding are 0, but there are margins. There are two types of solutions to this solution

1. Blank line space before deleting the code

The display:inline-block empty lines before the elements are removed, as in the following notation

2. The parent element font-size is set to 0, this direct view

7. Picture to set width and height

If the page has an IMG tag, then IMG recommends setting width and height. The goal is to ensure that the layout is not messy when the image is not loaded at the speed difference or other reasons.
The following chestnuts, a very common layout.

However, in case of any situation, the picture can not be loaded, the recommended way of processing is the first, showing a default picture, even if the default picture is not displayed, but also let the picture has a placeholder for the role, to ensure that the layout will not mess!

If the picture is not loaded, IMG does not set the width and height, it will be like the following, layout Chaos!

About setting up width and height , by the way, what time I
1.PC Station, the recommended properties for the IMG tag are set width and height . This avoids the loading of CSS and dislocation
2. Mobile station, recommended with CSS settings img width and height , because the cell phone station to do the adaptation, in the property settings width and height inflexible, such as the use of REM layout, in the properties there can not be set width and height .
3. If the picture is not fixed, but there is one max-width and max-height , then it is recommended to set the width and height on the img parent element. IMG is based on the and settings of the parent element and width height max-width max-height .

8. Center any element vertically

It's just a picture, not an explanation.

8-1.table-cell

8-2.flex

8-3.position,transform

8-4.position,margin

This method is not recommended, because this style, .p2 the width of the height must be set, or is 100%; for example, set the top:0;bottom:0; effect and settings height:100%; are the same. If you want to avoid it, you have to set it height .

9. Pre-loading images

This is said to preload, not lazy loading. First of all according to my personal understanding of popular science, lazy loading and pre-loading differences.

Lazy Loading: When the page loads, load a portion of the content (typically loading first screen content first), and other content wait until the loading time to load!

preload: When the page loads, load a portion of the content (typically loading first screen content first), other content wait until the first load of content (usually the first screen content) loaded, and then loaded.

Two ways, are to reduce the user to enter the site, faster to see the content of the first screen!

Below the chestnut, this #preloader element is added to the HTML, you can implement the properties of the CSS to background preload the picture to the outside of the screen background. As long as the paths to these pictures remain the same, when they are called elsewhere on the Web page, the browser uses the preloaded (cached) picture during the rendering process. Simple and efficient, no JavaScript required.

#preloader {/    * * requires a pre-loaded picture */    Background:url (image1.jpg) no-repeat,url (image2.jpg) No-repeat,url (image3.jpg) No-repeat;    width:0px;    height:0px;    Display:inline;}

However, there is a problem because #preloader preloaded images are loaded with other content on the page, increasing the overall load time of the page. So we need to use JS control

function Preloader (urlarr,obj) {    var bgtext= ';    for (Var i=0,len=urlarr.length;i<len;i++) {        bgtext+= ' url (' +urlarr[i]+ ') no-repeat, ';    }    Obj.style.background=bgtext.substr (0,bgtext.length-1);} Window.onload = function () {   preloader ([' image1.jpg ', ' image2.jpg ', ' image3.jpg '],document.getelementbyid (' Preloader '));}

The principle is also very simple, is to let the first screen of the picture loaded, and then load other pictures. By #preloader Setting the background image, loading the desired picture, and then the page needs to load these images, the image is taken directly from the cache, do not need to get the image via HTTP request, so load quickly.

10. Use the * wildcard character with caution

When you do a Web page, you often reset the style using the following two ways to eliminate the default layout of the label and the rendering of the same label for different browsers.

*{margin:0;padding:0;}

In this way, the code is small, but the performance is poor, because when rendering, to match all the elements on the page! Many of the underlying styles do not have elements such as margin padding , and p li so on. Are all matched, absolutely not necessary!
Here's another way to see it.

body,dl,dd,h1,h2,h3,h4,h5,h6,p,form,ol,ul{margin:0;padding:0;}

This way, the code is slightly more, but the performance is better than the above way, in the rendering, only match the body,dl,dd,h1,h2,h3,h4,h5,h6,p,form,ol,ul elements inside, these elements with margin and padding , need to reset!
Look again at the example:

. Test * {color:red;}

Match all the elements in the document, and then step up to match the elements of class test until the root node of the document

. test a {color:red;}

Match all the elements of a in the document, and then step up to match the elements of class test until the root node of the document

Two ways, which is better self-evident, so in the development of the time, it is recommended to avoid the use of a wildcard selector.

11. Merging, compressing CSS

This is nothing to explain, is to compress and merge CSS.

The first compression of the CSS, in addition to the use of tools, such as gulp,webpack, such as the code compression, the space and newline are removed. One more suggestion is attribute shorthand.

Like what

Margin-top:0;margin-right:10px;margin-bottom:10px;margin-left:10px;background-image:url (' test.jpg '); Background-position:top center;background-repeat:no-repeat;border-width:1px;border-style:solid;border-color:# 000;color: #0099FF;

Can be replaced by the following

margin:0 10px 10px 10px;background:url (' test.jpg ') no-repeat top center;border:1px solid #000; color: #09F;

As for the merger, I gave several suggestions according to my own development habits:
1. Merging common styles, such as the item's head, bottom, sidebar these are generally common, which can be written on a common style sheet, for example main.css .
2. The above-mentioned main.css is that each page needs to be introduced, and the style reset table reset.css is also required for each page, then the proposed MAIN.CSS and RESET.CSS merged into a file, to the page introduction! Reduce requests!
3. The corresponding style of each page is a separate file, for example, the homepage corresponds to index.css . The style that corresponds to the Product List page is product-list.css . Then index.css only in the homepage introduction, other pages are not introduced, because the introduction of pure waste request resources! Other pages corresponding to the style is also this way of processing! index.css, and product-list.css other pages of the style of the preservation of a separate file, not to be combined processing!

12.css in head Introduction

The browser will not start rendering the entire page until all the stylesheets have been loaded, and the browser will not render any content on the page until the page is blank. That's why you put stylesheet on your head. If placed at the bottom of the HTML page, page rendering is not just waiting for stylesheet loading, but also waiting for the HTML content to be loaded, so that the user can see the page later.

13. Avoid using @import

There are two ways to introduce CSS style files, one is an link element and the other is @import . Here, my advice is to avoid using @import . Because @import it affects the browser's parallel download, the page adds additional latency when loading, adding extra round-trip time. and multiple @import may cause the download order to be disordered. A CSS file, for example, index.css contains the following content: @import url("reset.css") . Then the browser must first download, index.css parse, and execute before downloading, parsing, and executing the second file reset.css. The simple workaround is to use <link> overrides @import .

14. Think how to write code from PSD file

Received, do not need to be eager to map, first look at the PSD file. Think about how to typesetting, those modules can be made public module, module should be named, write style, etc.
When we get the PSD to the designer, first of all, do not rush to write CSS code, first to the entire page analysis, first think about the following points:
(1) Analysis of which modules are common, common modules have head, bottom, menu bar, hover button and so on
(2) The analysis module has what style, the common style is extracted, common styles include common state style, such as buttons, input boxes, drop-down boxes, such as public check state, disable the state style and so on.

15. Small Icon Processing scheme

A website, there will certainly be a lot of small icons, for these small icons, the current solution has two, Csssprite (sprite), font icons, turn the picture into Base64. Here's a comparison of the two ways!
csssprite: A PNG image is synthesized for all icon images, with the width of the node set, plus bacgroud-position. Display the required icon in the background map, if a website has 20 icons, then request 20 times, using Csssprite, only need to request once, greatly reducing the HTTP request. The disadvantage is that the management is not flexible, if you need to add an icon, you need to change the image of the source files, icon positioning should also be standardized, or easily interfere with the positioning between the pictures!
font icon: Simple and rough understanding is to treat all the icons as a font processing! So you don't have to ask for pictures. Usually use class to define the icon, to replace the icon, only need to change the style name, easy to manage, semantic, flexible zoom out, and will not cause distortion. But only monochrome images are supported.
Base64: Another way is to turn the small icon image into Base64 encoding, so that you can not request the picture, the base64 code directly into the JS or CSS inside, you can prevent some relative path, Or the picture is not small deleted and other problems caused the picture 404 error. But find a way to generate a bunch of base64 codes. In general, images below 8K are converted to base64 encoding. If a 50K image is converted to base64 encoding, then the base64 encoding of more than 65,000 characters will be generated, and the size of the characters will be nearly 70K! The suggestion is: the image below 8K is converted to base64 encoding.

16. Do not nest or write tags in front of the ID selector

1.ID on the page is inherently unique and other people's weight is so large, the front nesting ( .content #test ) is completely wasteful performance. and write more meaningless code! Although this is a sentence, but still someone to make such a mistake!
2. In addition to nesting, there is no need to add tags or other selectors in front of the ID. Like, p#test or .test#test . Both of these methods are completely superfluous, because the ID is unique on the page. The front plus anything is superfluous!

17. Draw common styles into common styles

The long paragraph same style is extracted as a common style use, such as commonly used to clear floating, a single line beyond the display ellipsis, more than one line beyond the ellipsis and so on.

Chestnuts as follows

/* Out of ellipsis *//*<p class= ' text-ellipsis ' ></p>*/.text-ellipsis{  Overflow:hidden;  White-space:nowrap;  Text-overflow:ellipsis;} /* Clear floating *//*<p class= ' Clearfix ' ></p>*/.clearfix:after {    display:block;    Content: ";    Clear:both;    height:0;}

Optimization of 18.CSS3 Animation

In one of my previous articles (mobile Web development issues and optimization summary), there are also recommendations for optimization that have been written about this, and the previous two recommendations are:
1.CSS3 animations or transitions as much as possible using transform and opacity to implement animations, do not use left and top .
2. Animation and transition can be css3 resolved, do not use js . If complex animations can be used css3+js (or html5+css3+js ) in conjunction with development, the effect is only unexpected and cannot be done.

Add one: Animation should not be too much, especially mobile website, otherwise there will be performance problems, such as the CPU is occupied full, dropped frames and so on. Also, it is not recommended to use hardware acceleration for every element.

Reference Links:
CSS Animation Performance Optimization
CSS3 Animation Performance Optimization
Hardware acceleration of CSS animations
Web animations

19.body Set Minimum width

This is the problem that will occur at the PC station and should be known to everyone. Here's a quick word!
For example, the following chestnut, a Web site, page content width is 1200px. It looks normal, nothing special.

If this time, reduce the page window. Less than 1200px, scroll bars appear on the page, then drag the scroll bar to the far right

This is not to find that the top of the picture and the background is a part of the fault! To solve this problem is also very simple, is to body add min-width . The value is the value of the page width.body{min-width:1200px;}

Repeat the previous action, regardless of how the browser window size, is normal

The problem arises because, for example, when the window shrinks to 900px, it is less than 1200px of the content width. The horizontal scroll bar appears, but body the width is 900px. At this point, if there are elements (the gray area of the slice and the pink picture) is relative body to the width set 100%, then the width of these elements is actually 900px. So there will be the vision of those faults! The solution is to body add min-width . Make body the width minimum not less than the width of the content!

20. Summary

Here's a summary of my suggestions and performance optimizations for CSS writing. CSS is definitely not the kind of language that can be used as long as it is available, or as long as the layout can be done with CSS. CSS gives me the feeling that the start is very simple, but if you want to use good CSS, still have to take the time to study. CSS or CSS3, can optimize the things there are many, with good CSS or CSS3 can write a lot of JS code, do out of things is also very magical, we still have to continue to learn the knowledge!
If you feel that my article is not written in any place, wrong, please correct me. If there are any other suggestions, welcome guidance, let us communicate with each other, learn from each other, progress together! Finally, I wish you a happy holiday!


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.