How to write elegant CSS code? Go

Source: Internet
Author: User
Tags add numbers border color sublime editor sublime text sublime text editor

For the same project or a Web page, although eventually every front-end development engineer can achieve the same effect, the code they write must be Different. Some elegant, look clear, the code is extensible, such code is conducive to teamwork and later maintenance, and some confusion, although the ultimate effect, but obscure, obviously the team members in reading such code is not easy, and more detrimental to the maintenance of the Later. So how do you write elegant code? Below I will be a very small project on the following aspects of the simple expression of their own views, if there is something wrong, hope to Criticize.

    • How to organize a project.
    • How to write clear and understandable HTML Code.
    • How to write elegant CSS code (emphasis).

The first part: how to organize a project.

  When we take over a small project of a confession wall, how do we sort it out? is to put all the HTML files, CSS files, js files and pictures, and so on clutter together? well, Let's see what It's like.

Maybe you'll think It's nothing? The file can be found, but you try to open it in the sublime editor to see what the effect is:

(supplementary note: bo friend @tabweng suggested that the file name do not use Chinese language and try to use english, thank you, I hope you can also pay attention to this problem.) )

 did you find it confusing?! also, What if the project is bigger? Do you need more HTML files, css files, js files, and pictures? Can you make sure that you find every file you want and edit it smoothly? clearly, obviously, No. So for this kind of project, my suggestion is that you can categorize different file types, put the same type of files in a folder, and then put all the files in a folder, as shown in:

  

In this way, opening the above file in the sublime text editor will also become clearer as follows:

In this way, we can easily find, edit, maintain our code! of course, for different projects, how to structure and collation is different, we should specific problem specific analysis, here is just a description of the general small project can follow the Practice.

Part Two: how to write clear and understandable HTML code

HTML specification, i in the blog "HMTL Code specification" did a detailed introduction, we are interested to See. Here we briefly review the specification and describe in my opinion a holistic approach to writing HTML Code.

1. When writing html, the most basic overall structure is indispensable, including <! DOCTYPE html>

The code structure and visual order of 2.HMTL are basically consistent, that is, the HMTL structure is written in the visual order from left to right from top to Bottom. My suggestion is: you can first according to the visual manuscript, from the big picture, the main parts of the written out, such as the header part, main part, side part, footer part, that is, the entire structure first, and then one by one to fill in the contents of the internal, Instead of the first part of the header and then write the main section, the main part of the complete writing side part of ... Because the idea of the former will be clearer.

3. The structure layer (structural layer), The presentation layer (behavior layer), The behavior layer (presentation layer) are separated, avoiding the inline, that is, using script to introduce the JS file (note: the browser rendering page is top-down, JS files are sometimes introduced in </body> before, and sometimes in the head, this part can be seen in my blog "explore mobile development", using link to introduce CSS Files.

4. Maintain a good tree structure, that is, each block-level element has a different line, using the tab indent (relative to the parent element). If not block-level elements, such as <a><span>, write them in one LINE.

5. You can use blank lines between different sections (such as header, main, footer), and do not use extra empty lines within a module, which in fact follows the principle of intimacy in DESIGN. (recommended Front-End engineers can see the "write to everyone read the design book", very GOOD)

6. In the HTML code you think it may not be very good to understand the place to annotate such as:<!--some comments---.

The third part: how to write elegant CSS Code.

It is important that the code of the CSS is clear, and this part is the main introduction.

One: CSS Classification method

Usually a page we only refer to a css, but for larger projects, we need to classify the CSS File.

According to the nature and use of css, we can divide the css file into "common style", "special style", "skin style", and refer to it in Order. So what are they, respectively?

    • public style is the most important part, for smaller projects, we only introduce a css, this CSS style is a common style, generally include: "label reset and set default" (to eliminate differences between different browsers), " Unify calls to the background map and clear floating or other long styles that need to be processed uniformly (so that each is not processed separately), Web site General layout, common modules and their extensions, symbols and their extensions, feature class styles, skin class Styles. This will be explained in detail later.
    • Special style is for a high maintenance of the column or a page with a large difference in the overall web site to introduce such a special style, to facilitate our maintenance.
    • Skin Style is the product needs to change the skin function, then we need to color, background and so out of the place, easy to Manage.

CSS file We are divided into public style, special style, skin style, then in the CSS file inside how do we classify it? ( This section is focused )

    • resets and the default CSS code . This is to eliminate the default style and browser differences, and to set the initial style of the partial label to reduce the duplication of labor behind. you can set up according to your own website requirements, or you can use some of the initialization code that someone else has written, such as: the CSS initialization code provided by Yahoo! Engineers. This part of the code is placed at the top of the Css.
    • Unified Processing of CSS Code. Here you can call the background map uniformly and clear the float (refer to the more general layout, module, The original inside the clear), in fact, Yahoo engineers provide CSS initialization code to clear the floating CSS Code. This part of the code is placed underneath the reset and default CSS Code.
    • Layout (grid): We divide the page into several chunks, usually with the head, body, main bar, sidebar, tail, etc. Common!
    • Module: a larger whole that can be reused in a semantic format. such as navigation, login, registration, list, comment, search and so On. Common!
    • Component (unit): usually a small, non-divided individual, which is reused in various modules, such as buttons, input boxes, loading, charts, etc. Common!
    • Function: to facilitate the use of some commonly used styles, we peel these high-usage styles out and use them on demand, usually with fixed styles such as clear float. Not used, not abused!
    • Skin: for a skin-changing site needs to use, the skin type of the style out, Non-skin-type website can not be abused, not commonly used.
    • Status: some state class Styles. Not Used.

For the following types of internal classification, we first have an impression, and later I will explain how to use it.

second, CSS naming rules

  Important: use the class selector to discard the ID Selector. Because the uniqueness of the ID in a single page leads to the inability to reuse if the CSS is written with the ID selector, and the class has the advantage of reusability, and the private degree is not high. therefore, I will generally choose the ID in HTML for javascript, but in CSS only use class, an ID is not used. This actually separates the performance from the behavior, not the Mix.

how to write class in an HTML file: prefix with a single letter + "-". for Example: for the header part, we can write this:

1 <divclass="g-header"></div>

So what is a "single letter"? is actually the first letter of the layout (grid) in the CSS internal classification method that we have just introduced, and the advantage is that we can clearly know what the role is in the CSS code by the first letter, that is, see the name of the Idea. so, for the modular module we can write This: <div class= "m-log" ></div>. This div is the login box for this module. For the component part, i.e. the individual that cannot be divided, we can write . For the function part, we can write this: <div class= "f-clearfloat" ></div>. For the skin part, we can write this: <div class= "s-changeskin" >. where g, m, u these three initials are the most we use the first letter, the other initials should be used according to the Situation. Note 1: in css, the selector of a style is always preceded by The. G. m-u f-s five classes above, and then the descendant selectors are used Inside. Note 2: This is not to say that all classname need to add these prefixes, for some elements that do not belong to these, we can completely without prefix, as a descendant selector to Use.

So how do you use the descendant selector? We have agreed that class selectors that are not prefixed with a single letter + "-" and have a length greater than or equal to 2 are descendant Selectors. Such as:. G-date. u-rightarrow{float:right;} This is inappropriate, we write Directly. u-rightarrow{float:right; Can. and a semantic tag can also be a descendant Selector. Such as. M-list li{}. the previous sentence that is not a semantic label as a descendant selector is inappropriate, such as:. m-list div{}, such a way of writing is likely to cause Pollution.

In addition, we should pay attention to: in naming should be as simple as possible without losing semantics. As shown Below:

  

For different class names with the same semantics, we can directly add numbers or letters to distinguish them (for example,. m-list1,. m-list2, which are list modules, all by adding numbers that represent different list modules).

Three: CSS Code format

1. selectors, attributes, and values are all Lowercase.

This is critical: according to the XHTML specification, all tag attributes and values are in lowercase, and we know that XHTML is more standard, so it's best to follow it, so that selectors must be lowercase. Since then we can not use the camel style to write the class name, such as Class= "u-leftarrow" is actually not standardized, preferably written class= "u-left_arrow", can also express the same meaning.

2. Single-line completion of a selector Definition.

Advantages: easy to find and read the selector, but also easy to insert a new selector and editing, easy to identify the Module. more importantly, The extra spaces can be removed, making the code compact to reduce line breaks. imagine, If each row has only one property name and attribute value, then for a large project, it is difficult to do the selector to find and read, and use a line to write a selector, then it is possible to shorten the 1/6 to 1/10, which is very objective.

  

3. The last value also ends with a semicolon.

in fact, the value before the end of the curly brace can omit the semicolon, but doing so will cause unnecessary errors and hassles in the modification, addition, and maintenance Work. For example, to add a property at the end, and if you didn't add a semicolon at the end, you would have to add a semicolon before the newly added attribute, or it would be an error, such as when one of my posts added JSON data to the box to solve the Chinese font display.

  

4. Omit units with a value of 0

Pros: You can save unnecessary bytes and for readability, we abbreviated 0px, 0em, 0%, and so on to 0. as shown below:

  

1 .m-box{margin:010px; backgrond-position:50%0;}

  

5. Use 16 to represent the color value, where the letters are capitalized and abbreviated as Possible.

Unless you use RGBA when you need transparency, it is written in #ffffff and as short as possible, such as #fff. Uppercase is used because it is more readable and has the benefit of compression, while abbreviations are intended to reduce unnecessary bytes.

(supplementary note: bo friend @batsing pointed out that the use of 16 in the PC side of the color, IE8 and the following incompatible, thank you, I hope you can also pay attention to this Problem. )

6. Write according to the order of importance of the Attribute.

In the 2nd above we said we should finish writing a selector in one LINE. If we do not follow a certain writing order, then the code written out must be chaotic, then how to write elegant CSS code it? In this case, you need to write according to the order of importance of Attributes. As shown in the Following:

Note: only follow the horizontal order, that is, to write the positioning layout class properties, in the writing box model, such as its own properties, and finally write the text class and decorated class Properties. also, If there is an association between attributes, do not separate the write as Follows.

1 .m-box{position:relative;height:20px;line-height:20pxpadding:5px;color:#000;}

The height and line-height are related, we try not to write separately.

7. Private in front, standard in the rear.

Write a property with the Browser's private flag and write the properties of the Standard. Because of the private property, the browser itself has not been normalized, standard properties are not Available. If one day the properties of the browser are normalized, then the standard properties can be used, and if we write the standard properties, and then write the private property, it is possible to cause the private property to override the standard Properties. So private in the former, the standard after the wording is to take into account the problems that may arise later.

Such as:

1 .m-box{-webkit-box-shadow:00 0 #000;-moz-box-shadow:0 0 0 #000;box-shadow:0 0 0#000;}

  

8. Selector Level

!important> inline style style>id selector > class, pseudo Class and property selector > tag Selector and pseudo element selector

  

9.CSS Internal Order

I think, for a web page, when we write css, we can be divided into several parts to write, such as the header part of the CSS code, the main part of the CSS code, parts separated by a space and respond to the comments, which is more conducive to our reading and later maintenance, as shown below.

10. Optimization Scheme: for the values that can be abbreviated, we try to use abbreviated form, which helps to reduce the size of the CSS file and increase readability and maintainability. And it is best to minimize the properties of redundancies that do not actually Work. Sometimes we combine a series of selectors that define the same or have the same value as most of the attributes (using Commas) to define them uniformly, which can save you a lot of bytes and valuable Time.

FOUR. naming recommendations for class selectors

As mentioned earlier, when naming classname, it should be named after its function and function, rather than using text that is not semantically or colored or left or right.

1. for layouts, Use. g as the prefix, usually with the following recommended Notation.

Head: header or head

Body: body

Tail: footer or foot

Main Column: Main

Sidebar: side

Box Container: wrap or box

Main column Sub-container: Mainc

Side bar Sub-container: Sidec

2. For the module, i.e.. m as the Prefix. components,. u as prefixes, usually with the following recommended Notation.

Navigation: Nav

Sub-navigation: Subnav

Menus: Menu

Tab: tab

Title Area: head or title

Content Area: body or content

Listing: List

Table: table

Forms: form

Rank: Top

Hotspot: Hot

Login: Login

Logo: logo

Ad: adervertise

Searches: Search

Slide: Slide

Help:

Press: News

Download: Download

Register: Register or Regist

Vote: vote

Copyrights: Copyright

Result: result

Buttons: button

Inputs: input

3. for functions, which are prefixed with. f, it is usually recommended as Follows:

Clear Float: Clearboth

Float Left: Floatleft

Floating right: Floatright

Overflow Hide: Overflowhidden

  

4. for colors, which are prefixed with. s, it is usually recommended as Follows:

Font color: fontcolor

Background: background

Background color: backgroundcolor

Background image: backgroundimage

Background positioning: backgroundposition

Border Color: bordercolor

  

5. For the status, which is prefixed with. z, it is usually recommended as Follows:

Checked: selected

Present: Current

Show: Show

Hidden: Hide

Opening: Open

Close: Close

Error: Error

Not available: Disabled

V. Use the CSS selector for errors that often occur.
      • . class{} cannot use a style without a category as the primary selector, it can only be used as a descendant selector
      • . m-xxx div{} cannot use a non-semantic sticky note as a selector, resulting in a large area of pollution
      • G-ZZZ. m-xxx{} General category selectors should not include category selectors in descendant selection
      • . m-xxx. main Mainc. nav li{} do not write the selector too long, because the more complex the structure of the selector, the more expensive the browser consumes, and it is recommended to write within 3 lengths.

How to write elegant CSS code? Go

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.