Summary of methods for optimizing and improving performance in CSS

Source: Internet
Author: User
CSS optimization is mainly four aspects:

    1. Load performance
      This aspect related to the best practice too much, on-line search is a bunch of information, such as do not use import Ah, compression ah and so on, mainly from the reduction of file volume, reduce congestion loading, improve concurrency, any hint can not escape these several big directions.

    2. Selector performance
      However, the impact of selector on the overall performance can be neglected, selector is more standardized and maintainability, robustness, few people in the actual work will be the selector performance as a focus on the object, but also like GitHub this share said that the same- It's better to know than not to know.

    3. Rendering performance
      Rendering performance is the most important object of interest for CSS optimization. Too much page rendering junky? See if you're using a lot of Text-shadow? is the font anti-aliasing open? How is CSS animation implemented? Do you use GPU acceleration wisely? What, you used the flexible Box Model? Have you tested the effect of changing layout strategy on render performance? This aspect of search CSS render performance or CSS animation performance also have a bunch of data to reference.

    4. maintainability, robustness
      Is it reasonable to name? Is the structure level design robust enough? Have you abstracted the style? Elegant CSS will not only affect the later maintenance costs, but also the load performance and other aspects of impact. This aspect can find some oocss (not say want to use OOCSS, but say to know more about) and so on different CSS strategy information, learn from each other.

NO2

"CSS code refactoring and optimization Path"

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 CSS will be more and more, Eventually plunged 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

In front of the purpose of the CSS code refactoring, now for some how to achieve these basic methods, these methods are easy to understand, easy to implement some of the means, we usually may also 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.

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 functionality. Let's talk about some common methods.

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: Header

Content: Content/container

Tail: Footer

Navigation: Nav

Sidebar: Sidebar

Column: Column

Page perimeter control overall layout width: Wrapper

Middle: Left Right center

Login Strip: Loginbar

Logo: Logo

Ad: Banner

Page body: Main

Hotspot: Hot

Press: News

Download: Download

Sub-navigation: Subnav

Menus: Menu

Sub-menu: submenu

Searches: Search

Links: Friendlink

Footer: Footer

Copyrights: Copyright

Scrolling: Scroll

Contents: Content

Article List: List

Hint Message: MSG

Tip: Tips

Column Title: Title

Join: Joinus

Guide: Guides

Services: Service

Registration: Regsiter

State: Status

Vote: Vote

PARTNER: Partner

Navigation: Nav

Main navigation: Mainnav

Sub-navigation: Subnav

Top Navigation: Topnav

Side navigation: Sidebar

Left navigation: Leftsidebar

Right navigation: Rightsidebar

Menus: Menu

Sub-menu: submenu

Caption: Title

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 to improve the CSS maintainability, put forward some of the code and methods of writing CSS. 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 forcss. 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.

Summarize

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.

NO3:

CSS performance optimization of a lot of places, combined with the above several great God's answer, summarized as follows:
1. Careful use of high-performance properties: floating, positioning;
2. Minimize page reflow and redraw
Rearrange the order in which CSS is written:
Location: Positon, Top, left, Z-index, float, dispay
Size: width, height, margin, padding
Text series: Font, line-height, color, letter-spacing
Background border: background, border
Others: anmation, transition
Redraw: Border, outline, background, Box-shadow, can use Background-color, try not to use background;
3. Remove the null rule: {};
4. The property value is 0 o'clock, no unit;
5. Attribute value is floating decimal 0.**, can omit 0 before the decimal point;
6. Standardize the various browser prefixes: Front with browser prefix. The standard attribute is behind;
7. Do not use the @import prefix, it will affect the loading speed of CSS;
8. Make full use of CSS inheritance properties to reduce the amount of code;
9. Abstract public pattern extraction, reduce the amount of code;
10. The selector optimizes nesting, avoids the level too deep;
11.CSS Sprite chart, the same page similar parts of the small icon, easy to use, reduce the number of page requests, but at the same time the picture itself will become larger, when used, the pros and cons to consider clearly, and then use;
12. Place the CSS file on top of the page

.....

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.