[CSS] teaches you how to write efficient and clean CSS code-CSS Optimization

Source: Internet
Author: User
Tags website performance
ArticleDirectory
    • 1. Use reset but not global Reset
    • 2. Good naming habits
    • 3. Code abbreviations
    • 4. Use CSS inheritance
    • 5. Use multiple Selector
    • 6. Proper code comments
    • 7. Sort your CSS code
    • 8. Keep CSS readable
    • 9. Select a better style property value
    • 10. Replace @ import with <link>.
    • 11. Use an external style sheet
    • 12. Avoid using CSS expressions)
    • 13. Code Compression

CSS is not difficult to write, but it becomes difficult to manage in large projects. In particular, different people have slightly different CSS writing styles, making it even harder for teams to communicate, this section summarizes how to implement efficient and clean CSS.CodePrinciples.

CSS Optimization Principles

1. The page layout is not affected.

2. Remove unnecessary styles

3. Merge the same style

4. Minimize the style size

Common Problems in CSS styles

1. The style except the body is rewritten with the same style as the body, for example:

1 Body{Font-size:12px;Color:Red;}2 H1{Font-size:16px;Color:Red;}

H1 has inherited the attributes in the body during page parsing, so color: red; there is no need to rewrite it again.

2. The value of 0 plus unit is the same as that of no plus unit, for example:

1 H1{Margin:0px;}2 H1{Margin:0;}

The above two styles are completely equivalent, and the style below is better written.

3. There is no need to write exactly the same style twice. For example:

 
1 H1{Color:Red;}2 H2{Color:Red;}

The above two styles are the same. We can merge them:

1 H1, H2{Color:Red;}

4. Abbreviations of some styles, such as margin and padding

 
1 H1{Margin-top:5px;Margin-Right:5px;Margin-bottom:5px;Margin-left:5px;}

The above style can be abbreviated:

 
1 H1{Margin:5px;}

5. The color can be abbreviated, for example:

1 H1{Color:#000000;}

The above style can be abbreviated:

 
1 H1{Color:#000;}

You can also enter it as follows:

 
1 H1{Color:Black;}
Main benefits of CSS Optimization

1. improve ease of coding for CSS files

2. Reduce the CSS file size

3. It can accelerate the loading speed of browsers.

Implementation of efficient and clean CSS Code principles 1. Use reset but not global Reset

The default attributes of different browser elements are different. You can use reset to reset some default attributes of browser elements to achieve browser compatibility. However, do not use global Reset:

1 *{Margin:0;Padding:0;}

This is not only because it is a slow and inefficient method, but also causes unnecessary elements to reset the outer and inner margins. We recommend that you refer to Yui reset and Eric Meyer. Reset is not static. You need to modify the reset according to different project requirements to achieve browser compatibility and operation convenience. This is the reset.css I use.

2. Good naming habits

No doubt, the code is messy or the code for naming without definition. Anyone who looks at it will be crazy. Code like this:

 
1 . Aaabbb{Margin:2px;Color:Red;}

I don't want to name a class like this in my project even for beginners.

3. Code abbreviations

CSS code abbreviations can speed up code writing and streamline the amount of code. There are many attributes that can be abbreviated in CSS, including margin, padding, border, Font, background, and color value. If you have learned the abbreviation of code, the original code is as follows:

1 P{2 Font-family:Arial, Helvetica, sans-serif;3 Font-size:1.2em;4 Line-height:1.4em;5 Padding-top:5px;6 Padding-bottom:10px;7 Padding-left:5px;8}

It can be abbreviated:

1 P{2 Font:1.2em/1.4em Arial, Helvetica, sans-serif;3 Padding:5px 0 10px 5px;4}

For specific CSS abbreviation rules, click the following address:

Http://www.cnblogs.com/yjzhu/archive/2012/11/05/2754877.html

4. Use CSS inheritance

If multiple child elements of the parent element on the page use the same style, it is best to define their same style on the parent element so that they can inherit these CSS styles. In this way, you can maintain your code and reduce the amount of code. The Code is as follows:

1 # Content Li{Color:Red;}2 # Content P{Color:Red;}3 # Content H1{Color:Red;}

It can be abbreviated:

 
1 # Content{Color:Red;}
5. Use multiple Selector

You can merge multiple CSS selectors into one, if they have a common style. In this way, the code is concise and saves you time and space. For example:

1 H1{Font-family:Arial, Helvetica, sans-serif;Font-weight:Normal;}2 H2{Font-family:Arial, Helvetica, sans-serif;Font-weight:Normal;}3 H3{Font-family:Arial, Helvetica, sans-serif;Font-weight:Normal;}

The preceding three styles can be merged.

H1, H2, H3{Font-family:Arial, Helvetica, sans-serif;Font-weight:Normal;}
6. Proper code comments

Code comments make it easier for others to understand your code and organize code comments reasonably to make the structure clearer.

You can choose to add a directory at the beginning of the style sheet:

1 /*------------------------------------2 1. Reset3 2. Header4 3. Content5 4. Sidebar6 5. footer7 -----------------------------------*/

In this way, you can easily find and modify the code structure.

The main content of the Code should also be properly divided, and the code should be annotated and explained where necessary, which is also conducive to team development:

 1  /*  ** Header **  */  2   # Header { Height : 145px ; Position : Relative ;} 3   # Header H1 { Width : 324px ; Margin :45px 0 0 20px ; Float : Left ; Height : 72px ;} 4   /*  ** Content **  */  5   # Content { Background : # Fff ; Width : Pixel PX ; Float : Left ; Min-height : 600px ; Overflow : Hidden ;} 6   # Content H1 { Color : # F00 } /*  Set Font color  */  7  # Content. Posts { Overflow : Hidden ;} 8   # Content. Recent { Margin-bottom : 20px ; Border-bottom : 1px solid # f3f3f3 ; Position : Relative ; Overflow : Hidden ;}9   /*  ** Footer **  */  10   # Footer { Clear : Both ; Padding : 50px 5px 0 ; Overflow : Hidden ;} 11   # Footer h4 { Color :# B99d7f ; Font-family : Arial, Helvetica, sans-serif ; Font-size : 1.1em ;}
7. Sort your CSS code

If all the attributes in the code can be sorted by letters, the search and modification will be faster:

 1   /*  ** Style attributes are sorted alphabetically **  */      2   Div { 3   Background-color :# 3399cc ; 4   Color : #666 ; 5   Font : 1.2em/1.4em Arial, Helvetica, sans-serif ; 6   Height : 300px ; 7   Margin : 10px 5px ; 8  Padding : 5px 0 10px 5px ; 9   Width : 30% ; 10   Z-Index : 10 ; 11 }
8. Keep CSS readable

Writing readable CSS makes it easier to search for and modify styles. In either of the following situations, which one is more readable.

 1   /*  ** Write a row for each style attribute **  */     2   Div { 3   Background-color : # 3399cc ; 4   Color : #666 ; 5   Font : 1.2em/1.4em Arial, Helvetica, sans-serif ; 6   Height : 300px ;7   Margin : 10px 5px ; 8   Padding : 5px 0 10px 5px ; 9   Width : 30% ; 10   Z-Index : 10 ; 11 } 12  /*  ** Write all style attributes in the same row **  */      13   Div { Background-color : # 3399cc ; Color : #666 ; Font : 1.2em/1.4em Arial, Helvetica, sans-serif ; Height : 300px ; Margin :10px 5px ; Padding : 5px 0 10px 5px ; Width : 30% ; Z-Index : 10 ;}

When there are some selectors with fewer style attributes, I will write a line:

1 /*** The selector attribute is rarely written in the same row ***/2 Div{Background-color:# 39C;Color:#666;}

This rule is not a hard rule, But no matter which method is used, I suggest always keep the Code consistent. Multiple branch writes with more than three attributes can be written into one row.

9. Select a better style property value

Some attributes in CSS use different attribute values. Although the effect is similar, there are differences in performance, such:

The difference is that border: 0 sets border to 0px. Although it cannot be seen on the page, the browser still renders border-width/border-color according to the default value of border, that is, the memory occupied.

While border: None sets border to "NONE", that is, none. When the browser parses "NONE", no rendering action is made, that is, no memory value is consumed. Therefore, we recommend using border: none;

Similarly, display: None hides the object. The browser does not render the object and does not occupy memory. Visibility: hidden.

10. Replace @ import with <link>.

@ Import is neither an XHTML tag nor a part of the Web standard. It is not highly compatible with earlier browsers and has some negative impact on website performance. Therefore, avoid using @ import

11. Use an external style sheet

This principle is always a good design practice. It is not only easier to maintain and modify, but more importantly, it can improve the page speed by using external files, because CSS files can generate cache in the browser. CSS built in the HTML document will be re-downloaded with the HTML document in each request. Therefore, in practical applications, there is no need to build CSS code into HTML documents.

12. Avoid using CSS expressions)

CSS expressions are powerful but dangerous methods to dynamically set CSS attributes. Internet Explorer supports CSS expressions since version 5th. In the following example, you can use a CSS expression to change the background color every hour:

 
1 Div{Background-color:Expression (new date (). gethours () % 2? "# B8d4ff": "# f08a00 ");}

As shown above, expression uses a javascript expression. The CSS attribute is set based on the calculation result of the Javascript expression.

The problem with expressions is that they are computed more frequently than we think. Not only when the page is displayed and scaled, but when the page is scrolling or even moving the mouse, it is re-computed. Add a counter to the CSS expression to track the computing frequency of the expression. You can easily move the mouse over 10000 times on the page.

If you must use CSS expressions, remember that they must be calculated thousands of times and may affect the performance of your page. Therefore, do not use CSS expressions unless you have.

13. Code Compression

When you decide to deploy the website project on the network, you need to compress the CSS, comment out the comments and spaces to make the webpage Load faster. To compress the code, you can use some tools, such as Yui compressor, to streamline the CSS code and reduce the file size to get a higher loading speed.

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.