The path of reconstruction and optimization of CSS code

Source: Internet
Author: User

The students who write CSS tend to realize that as the project size increases, the CSS code in the project will be more and more, and if the CSS code is not maintained in time, the CSS code will continue to be more and more. CSS code interleaved complex, like a huge spider web distributed in various locations of the site, you do not know how to modify this line of code will have any effect, so if you have to modify or add new features, developers often afraid to remove the old redundant code, and insurance to add new code, the ultimate disadvantage is that the project's CSS will be more and more , and eventually fell into a bottomless pit.

  The purpose of the CSS code refactoring

When we write CSS code, not only do the page design effect, but also make the CSS code easy to manage, maintenance. We have two main purposes for the refactoring of CSS code:

1. Improve Code Performance

2, improve the maintainability of the Code

  Improve Code Performance

There are two main points to improving the performance of CSS code:

1, improve the load performance of the page

Improve the load performance of the page, simply to reduce the size of the CSS file, improve the loading speed of the page, can make use of HTTP cache

2. Improve CSS code performance

Different CSS code, the browser to its resolution of the speed is not the same, how to improve the browser to resolve the CSS code speed is also our consideration

 Improve the maintainability of your code

Improving the maintainability of CSS code is mainly reflected in the following points:

1. reusability

Generally speaking, the overall design style of a project is consistent, the page must have several styles consistent but some different modules, how to reuse the CSS code as much as possible, add as little as possible new code, which is very important in the CSS code. If the CSS code is highly reusable, we may only need to write some different places, which is very helpful for page performance and maintainability, and for improving development efficiency.

2. Scalability

If the product adds a feature, we should ensure that the new CSS code does not affect the old CSS code and page, and that the old code is reused as little as possible by adding new code.

3. Modifiable

If a module product manager feel to modify the style, or to delete it, if the corresponding CSS code is not planned, after a period of time, the developer may have forgotten that the code is a few places, do not dare to modify or delete it, so that the CSS code is more and more, affecting the performance of the page, It also creates the complexity of the code.

 The basic method of refactoring CSS code

Before talking about the purpose of the CSS code refactoring, now let's talk about some of the basic methods of how to achieve these goals, which are easy to understand, easy to implement some of the means, we can usually unknowingly use it.

  Ways to improve CSS performance

First of all, how to improve the performance of CSS, according to page loading performance and CSS code performance, the main summary has the following points:

1, try to write the style in a separate CSS file, in the Head element reference

Sometimes for the sake of convenience or quick-fix function, we may write the style directly on the page's style label or directly inline on the element, although it is simple and convenient, but very detrimental to future maintenance. There are several advantages to writing code as a separate CSS file:

(1) Content and style separation, easy to manage and maintain

(2) Reduce page volume

(3) CSS files can be cached, reused, and maintenance costs are reduced

2, do not use @import

This means is already known, here simply mention, @import affect the loading speed of the CSS file

3, avoid the use of complex selectors, the less hierarchy the better

Sometimes the module of the project is more and more, the function is more and more complex, we write the CSS selector will be nested multilayer, more and more complex.

It is recommended that the selector should not be nested more than three layers, such as:

header. logo. Text {}

can be optimized into

. Haeder. Logo-text {}

The simple selector not only reduces the size of the CSS file, improves the loading performance of the page, but also makes the browser more efficient when parsing, and also improves developer productivity and reduces maintenance costs.

4, streamline the page style file, remove the unused style

Many times, we will merge all the style files into one file, but there is a problem: many other pages of CSS are referenced to the current page, and the current page does not use them, this situation will cause two problems:

(1) The style file is too large to affect the loading speed

(2) The browser will make extra style matching, affecting the rendering time.

The correct way to do this is to merge the CSS files used by the current page according to the CSS required by the current page.

PS: Merging into a file has one advantage: The style file will be cached by the browser and go to other page style files without downloading. This rule should be treated according to the scene, if it is a large project, should be merged into a different style file, if it is a simple project, it is recommended to merge into a file. If you cannot confirm the size of the project, it is recommended to separate the different style files, and it is convenient to merge later.

5. Reduce the amount of code with CSS inheritance

We know that some CSS code can be inherited, if the parent element has already set the style, the child element does not need to set the style, this is an effective way to improve performance.

Common properties that can be inherited, such as:

color,font-size,font-family, wait.

Non-inheritable such as:

Position,display,float, etc.

You can view the CSS online manual

Ways to improve maintainability

Improve the maintainability of the CSS code, simply to make it easy for developers to understand the CSS code, easy to modify it, do not break the original function. Let's talk about some common means.

1. Naming and Notes

Naming is a first step and an important step in improving the readability of your code. Many people have this experience: naming is one of the most frustrating things for programmers in writing code, especially for non-English-speaking developers, it's not easy to find a proper name. To improve your ability to name, you can look at other people's code. The following are some naming-related recommendations in CSS:

    head: Header02    content: content/container03    Tail: footer04    navigation: nav05    Sidebar: sidebar06    column: Column07    Page perimeter control Overall layout width:    about: Left right center09    login: Loginbar10    flag: logo11    ad: Banner12    page body: main13    hot: hot15    Download: download16    sub-navigation: subnav17    Menu: Menu18    submenu: submenu19    search: Search20    Links: friendlink21    footer: footer22    Copyright: copyright23    Scrolling: scroll24    content: Content25    Tags: tags26    Article list: list27    tip: Msg28 tips    : tips29    column title: Title30    Join: joinus31    guide: Guide32    Service: service33    registration: Regsiter34    Status: Status35    votes: Vote36 Partners    : partner37    navigation: nav38    Main navigation: mainnav39 navigation:    subnav40    Top navigation: topnav41    side navigation: sidebar42    left navigation: leftsidebar43    Right navigation: Rightsidebar44    Menu: Menu45 submenu    : submenu46    title: title47    Abstract: summary

2. Extracting Repeating styles

This method is easy to understand, simply to extract the same style into a separate class to reference, so that not only can simplify the size of the CSS file, but also less CSS code, easier to reuse and maintenance. For example, the following example:

The original code is this:

. About-title{margin:0 Auto 6rem;Color:#333;text-align:Center;letter-spacing:4px;font-size:2rem;}. Achieve-title{margin:0 Auto 6rem;Color:#fff;text-align:Center;letter-spacing:4px;font-size:2rem;}

The difference between the two styles is that the color of the text is different, we can extract its common style, and then set its different styles separately.

. Column-title {    margin: 0 auto 6rem; text-align: Center; letter-spacing: 4px; font-size: 2rem;} . about {    color: #333;} . Achieve {   color:#fff

Extracting common parts, and then referencing Column-title and about on the page separately, makes the code more concise and easier to maintain. This example is very simple, in fact, the project may have more complex situations, in short, should be as dry as possible, to extract the duplication of things.

3. Writing order

This writing order refers to the writing order of each style, and the following is the recommended CSS writing order

(1) Position attributes (position, top, right, z-index, display, float, etc.)

(2) Size (width, height, padding, margin)

(3) Text series (font, Line-height, letter-spacing, color-text-align, etc.)

(4) Background (background, border, etc.)

(5) Other (animation, transition, etc.)

The writing order does not have to follow the recommendations above, but according to your own habits, but it is best to ensure that the customary consistency, or the team should have a common code to comply with, so that later maintenance will be much easier.

The above is my personal summary of some simple way to write and refactor CSS code, we certainly do not have to adhere to this, there are different views and suggestions welcome to exchange!

 CSS Methodology

What is a CSS methodology? In short, some of the peers in order to improve the maintainability of CSS, put forward some of the specifications and methods of writing CSS code. They come up with some concepts that may sound big, but you might actually use these so-called CSS methodologies when you don't. Let me briefly introduce the next few more common CSS methodologies.

Oocss

Oocss (Object oriented CSS), as the name implies, is object-oriented CSS.

There are two main principles of OOCSS:

1. Structure and style separation

We must have encountered this situation, such as a page has a number of different functions of the button, the shape of the buttons are similar, but depending on the function will have a different color or background to distinguish. If the structure and style are not separated, our CSS code may be like this

. Btn-primary{width:100px;Height:50px;padding:5px 3px;background:#ccc;Color:#000;}. Btn-delete{width:100px;Height:50px;padding:5px 3px;background:Red;Color:#fff;}

These two or possibly more buttons have some different styles, but they both have the same size style and so on, and we extract their abstract parts, and the results are as follows:

. BTN {width:100px; height:50px; padding:5px 3px;} . Primary {background:Red; color:#fff;} . Delete {background:Red; color:#fff

This extracts the common style out, and then the buttons refer to both BTN and primary. In addition to reducing repetitive code refinement CSS, there is a benefit of reusability, if you need to add additional buttons, only need to write a different style, and btn with the use of.

(2) Separation of containers and contents

We usually write code that must have written this code

. Content H3 {    font-size:20px;     color:#333;}

Such code is that the content depends on the container, there is no separate code, that is, the H3 style depends on the. Content container, if the same style is used elsewhere, but its container is not. Content, then you might want to write it again. Something H3.

So OOCSS recommends separating containers and content, which can be modified to:

. Title {    font-size:20px;     color:#333

In this connection, I personally recommend that, as in the previous example, it fits the style and container separation. But for example, the following is the case:

. Menu Li {    font-size:12px;}

This style of Ul,li list, I think just as we have done, do not necessarily have to give a class to Li to set the style, that is,

. Menu-item {    font-size:12px;}

The Li tag of this page needs to refer to the Menu-item class.

Of course, whichever is better I am not sure, I prefer. Menu Li's writing, we think for ourselves.

This is OOCSS's two basic principles, here is just a brief introduction to OOCSS, if you are interested, please google to find relevant information.

 Smacss

What is SMACSS, its full name is scalable and Modular Architecture for CSS. Simply put, extensible and modular CSS architecture.

Smacss the style into 5 types: Base,layout,module,state,theme, let's simply say what each type refers to.

1. Base

Base style sheet, defines the basic style, we usually write CSS such as RESET.CSS is the basic style sheet, in addition I think clear floating, some animations can also be categorized as the base style.

2. Layout

Layout style, used to implement the basic layout of the Web page, the basic skeleton of the entire Web page.

3. Module

Different areas of the Web page have this different function, these functions are relatively independent, we can call it a module. Modules are standalone, reusable components that do not depend on layout components and can be safely removed without affecting other modules.

4. State

State styles, often used in conjunction with JS, represent a different state of a component or feature, such as a menu selection, a button unavailable state, and so on.

Regarding the state style, I personally feel that we should discuss the situation:

(1) The same state of the different components of the style is the same, such as the navigation menu of the head of the selected state style and the sidebar menu selected state style is the same, I think this part of the state style can be categorized as

(2) The unified state of the different components of the style is not the same, that is, two places the menu is selected, but they are different check style, this part of the style should not be considered as the state type, but should be placed in the corresponding module of its components.

5, Theme

Skin style, for the replaceable skin of the site, this is very necessary, separated the structure and skin, according to different skin application of different style files.

  BEM

BEM is the abbreviation of Block,element,modifier. Here are some of the three concepts:

(1) Block: In Bem's theory, a Web page is composed of blocks, such as the head is a block, the content is Block,logo is also block, a block may be composed of several sub-blocks.

(2) Element:element is part of a block, has a function, element depends on block, for example, in the logo, IMG is an element of the logo, menu item is an element of the menu

(3) Modifier:modifier is used to modify a block or element, which represents a change in the appearance or behavior of a block or element.

We write styles by using the BEM nomenclature as follows:

. block{}

. block-element{}

. block-modifier{}

. block-element-modifier{}

bem resolves the page to blocks and element, and then uses modifier to set the style based on the different states.

My understanding of BEM may not be in place, the view of BEM is mainly from two points:

(1) page CSS modularity, each block is a module, the modules are independent of each other

(2) Multi-level class naming, avoiding the nesting structure of selectors

 About CSS Methodology

The above mentioned CSS methodology, you will see that they actually have a lot of ideas are the same, such as:

1, the selection of nesting optimization

2. Modularization of CSS Code

3. Abstract CSS Code

...

These methodologies, when we learn, the most important thing is to understand its ideas, not necessarily to copy its implementation form, a variety of methods combined use.

  My own method of summarizing

Having talked so much, here's my summary of some key points in writing CSS code.

1, before writing code: from the PSD file

When we get the PSD to the designer, first of all, do not rush to write CSS code, the first analysis of the entire page, the main focus is the following:

(1) the page is divided into several modules, which modules are common, such as the head and the bottom, there are some menu bar and so on

(2) Analyze what styles each module has, extract common styles, notice whether public styles are global public (entire page public) or local public (public within modules), common styles include common state styles, such as public check state, disabled state, and so on.

2. Start writing code

Based on the analysis of the PSD file, we can begin to write code, I recommend smacss the style into different types of practice:

(1) The first step is to set the skeleton of the page, that is, the base style, layout style.

(2) The second step is to implement different modules in turn, where I recommend Bem's naming idea, but can nest one to two layers of the selector structure

3. Optimized code

I believe that when we complete the basic page effect, there will still be some repetitive or not concise code, this is to optimize the code, mainly in the extraction of duplicate code, as much as possible to streamline the code.

About the optimization of CSS code, I believe that we have a lot of their own views, welcome to exchange and discussion!

Source: http://www.cnblogs.com/lrzw32/p/5100745.html

The path of reconstruction and optimization of CSS code

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.