Performance optimizations for CSS

Source: Internet
Author: User

---restore content starts---

Xu Yuxi
Links: https://www.zhihu.com/question/19886806/answer/80432295

"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

Tags: tags

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 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.

---restore content ends---

Performance optimizations for CSS

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.