13 Tips to write good CSS code

Source: Internet
Author: User
CSS is not difficult to learn, but in large projects, it becomes difficult to manage, especially the different people in the CSS writing style slightly different, the team is more difficult to communicate, to summarize some how to achieve efficient and neat CSS code principles:

1. Use reset but not global reset

The default properties for different browser elements vary, using reset to reset some of the default properties of the browser element to achieve browser compatibility. It is important to note, however, that you do not use global reset:

*{margin:0; padding:0;}

This is not only because it is a slow and inefficient method, but also causes some unnecessary elements to reset margins and padding. Refer to the practice of Yui Reset and Eric Meyer in this recommendation. I have the same view as Eric Meyer, reset is not static, and the specific needs of the project to make appropriate changes to achieve browser compatibility and ease of operation. I use the reset as follows:

/** clear inner margin **/body, H1, H2, H3, H4, H5, H6, HR, P, blockquote,/* Structural elements structural elements */dl, DT, DD, UL, OL, Li,/* li St Elements list element */pre,/* text formatting elements literal format elements */form, fieldset, Legend, button, input, textarea,/* form Elem Ents table cell */th, TD,/* Table elements TABLE element */img/* img Elements picture element */{   border:medium none;   margin:0;   padding:0;  }/** Set default font **/body,button, input, select, textarea {   font:12px/1.5 ' Arial ', Tahoma, Srial, Helvetica, Sans-serif;} H1, H2, H3, H4, H5, h6 {font-size:100%;} em{font-style:normal;}/** Reset list element **/ul, ol {list-style:none;}/** Reset Hyperlink element **/ a {text-decoration:none; color: #333;} a:hover {text-decoration:underline; color: #F40;}/** resets the picture element **/img{border:0px; }/** Reset Table element **/table {border-collapse:collapse; border-spacing:0;}

2. Good naming habits

No doubt a messy or no semantic naming code, who will be crazy to see. Just like this code:

. aaabb{margin:2px;color:red;}

I think even beginners don't have to name a class like this in a real project, but it's also problematic to think about this code:


The problem is that if you need to change all the original red fonts to blue, then the changes will change to the style:

. Red{color:bule;}

Such a name would be confusing, and the same name would be called. Leftbar's sidebar can be cumbersome if you need to modify it to the right sidebar. Therefore, do not use the attributes of the element (color, position, size, etc.) to name a class or ID, you can choose the meaning of the name such as: #navigation {...}},.sidebar{...},.postwrap{...}

This way, no matter how you modify the style that defines these classes or IDs, it does not affect the connection between them and the HTML elements.

In addition, there is a situation, some fixed style, the definition will not be modified, then you do not have to worry about the name of the situation just said, such as

. alignleft{float:left;margin-right:20px;}. alignright{float:right;text-align:right;margin-left:20px;}. clear{ clear:both;text-indent:-9999px;}

So for such a paragraph

<p class= "AlignLeft" > I am a paragraph! </p>

If you need to change this paragraph from the original left-aligned to right-aligned, then you just need to modify its classname to alignright.

3. Code Abbreviations

CSS code abbreviations can improve the speed at which you write your code and streamline your code. In CSS there are many attributes that can be abbreviated, including margin,padding,border,font,background and color values, if you learn the code abbreviation, the original code:

li{     font-family:arial, Helvetica, Sans-serif;     Font-size:1.2em;     Line-height:1.4em;     padding-top:5px;     padding-bottom:10px;     padding-left:5px; }

It can be abbreviated as:

li{     font:1.2em/1.4em Arial, Helvetica, Sans-serif;     padding:5px 0 10px 5px; }

If you want to know more about how these attributes are abbreviated, you can refer to the common CSS abbreviation syntax summary or download css-shorthand-cheat-sheet.pdf.

4. Using CSS Inheritance

If multiple child elements of a parent element in a page use the same style, it is better to define their same style on their parent element and have them inherit the CSS styles. This way you can maintain your code well, and you can also reduce the amount of code. So the original code:

#container li{font-family:georgia, serif;} #container p{Font-family:georgia, serif;} #container H1{font-family:georgi A, serif; }

You can simply write:

#container {font-family:georgia, serif;}

5. Using multiple selectors

You can combine multiple CSS selectors for one if they have a common style. This is not only simple code but also saves you time and space. Such as:

h1{font-family:arial, Helvetica, Sans-serif, Font-weight:normal;} h2{font-family:arial, Helvetica, Sans-serif; Font-weight:normal; } h3{font-family:arial, Helvetica, Sans-serif; font-weight:normal;}

can be combined into

H1, H2, h3{font-family:arial, Helvetica, Sans-serif; font-weight:normal;}

6. Appropriate code comments

Code comments can make the structure clearer by making it easier for others to read your code, and to organize code annotations appropriately. You can choose to do the start of the style sheet by adding a directory:

/*------------------------------------     1. Reset     2. Header     3. Content     4. SideBar     5. Footer   -----------------------------------*/

So the structure of your code is straightforward, and you can easily find and modify the code.

The main content of the code should also be properly divided, even where necessary to comment on the code, which is also conducive to team development:

/***    Header  ***/#header {height:145px; position:relative;} #header h1{width:324px; margin:45px 0 0 20px; float: Left;  height:72px;}   /***    Content ***/#content {background: #fff; width:650px; float:left; min-height:600px; overflow:hidden;} #content H1{color: #F00}/* Set Font color */#content. posts{Overflow:hidden;} #content. recent{margin-bottom:20px; border-bottom:1px Solid #f3f3f3; position:relative; Overflow:hidden; }   /***    Footer  ***/#footer {clear:both; padding:50px 5px 0; overflow:hidden;} #footer h4{color: #b99d7f; Font-family:arial, Helvetica, Sans-serif; Font-size:1.1em; }

7. Sort your CSS Code

If the attributes in your code are sorted alphabetically, it's quicker to find the changes:

/*** style properties sorted alphabetically ***/p{     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; }

8. Keep the CSS readable

Writing a readable CSS will make it easier to find and modify styles. For the following two cases, which is more readable, I would like to make it clear.

/*** Each style property writes a line ***/p{     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; }   /*** All style attributes are written on the same line ***/p{background-color: #3399cc; color: #666; font:1.2em/1.4em Arial, Helvetica, sans-serif;< c17/>height:300px; margin:10px 5px; padding:5px 0 10px 5px; width:30%; Z-index:10; }

When it comes to selectors with fewer style attributes, I'll write a line:

/*** Selector attribute less write on the same line ***/p{background-color: #3399cc; color: #666;}

This rule is not mandatory, but no matter which one you use, my advice is to always keep the code consistent. Attributes are written in more than 3 lines, and can be written one line.

9. Select a better style attribute value

Some properties in CSS use different attribute values, although the effect is similar, when there are differences in performance, such as

The difference is that border:0 set border to 0px, although it is not visible on the page, but according to the border default value, the browser still renders the Border-width/border-color, that is, the memory value is already occupied.

and Border:none set border to "none" that is not, the browser to resolve "None" will not make a rendering action, that is, will not consume memory values. Therefore, it is recommended to use Border:none;

Similarly, the Display:none hidden Object Browser does not render, and does not consume memory. And the Visibility:hidden will.

10. Use <link> replace @import

First, @import is not part of the XHTML tag or Web Standard, it is not as compatible with earlier browsers and has some negative impact on the performance of the site. Refer to "High-performance Web design: Do not use @import". Therefore, please avoid using @import

11. Using an external style sheet

This principle is always a good design practice. Not only is it easier to maintain modifications, but it is more important to use external files to improve page speed because CSS files can generate caches in the browser. The CSS built into the HTML document is re-downloaded with the HTML document in each request. Therefore, in practical applications, it is not necessary to have CSS code built into the HTML document:

<style type= "Text/css" >     #container {...}     #sidebar {..} </style>

Or

<li style= "Font-family:arial, Helvetica, Sans-serif; Color: #666; ">

Instead, use <link> to import an external style sheet:

<link rel= "stylesheet" type= "Text/css" href= "Css/styles.css"/>

12. Avoid using CSS expressions (expression)

CSS expressions are a powerful (but dangerous) way of dynamically setting CSS properties. Internet Explorer supports CSS expressions starting with the 5th version. In the following example, a CSS expression can be used to switch the background color at one-hour intervals:

Background-color:expression (New Date ()). GetHours ()%2? "#B8D4FF": "#F08A00");

As shown above, JavaScript expressions are used in expression. CSS properties are set based on the results of the JavaScript expression calculations.

The problem with expressions is that they are calculated more frequently than we think. Not only when the page is displayed and scaled, it is recalculated when the page scrolls, or even when the mouse is moved. Add a counter to the CSS expression to track how often the expression is calculated. Easily move the mouse in the page can be more than 10,000 times the amount of calculation.

If you must use CSS expressions, be sure to remember that they are counted thousands of times and may have an impact on the performance of your pages. Therefore, avoid using CSS expressions in the non-forced way.

13. Code Compression

When you decide to deploy a Web site project to the Web, you'll want to consider compressing the CSS, commenting out comments and spaces to make the page load faster. Compress your code, you can use some tools, such as Yui Compressor

It can be used to streamline CSS code and reduce file size for higher loading speeds.

14. Summary

In this article, I try to summarize the principles of writing more efficient CSS code, but given my insight and limited energy, I still hope that these principles can help you better write and manage your CSS code, I do not know how you write CSS, do you have some skills to share? Give me a message thank you ~

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.