CSS code reconstruction and optimization, and css Reconstruction

Source: Internet
Author: User

CSS code reconstruction and optimization, and css Reconstruction

Author: @ langlang's blue fat man

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

Students who write CSS often realize that as the project scale increases, CSS code in the project will also increase. If CSS code is not maintained in time, CSS code will continue to grow. CSS code is staggered and complex, like a huge spider web is distributed in various locations of the website. You don't know what the impact of modifying this line of code will be, so if there are modifications or new features, developers often do not dare to delete the old redundant code, and add new code safely. The final disadvantage is that there will be more and more CSS in the project and eventually fall into a bottomless pit.

The purpose of CSS code Reconstruction

When writing CSS code, we should not only finish the page design, but also make CSS code easy to manage and maintain. We have two main objectives for CSS code refactoring:

Improve Code Performance

There are two main points to improve the CSS code performance:

1. Improve page loading Performance

To improve the page loading performance, it is simply to reduce the size of CSS files, increase the page loading speed, and make full use of http cache.

2. Improve CSS Code Performance

The speed at which the browser parses different CSS codes is also different. We also need to consider how to improve the speed at which the browser parses CSS codes.

Improve code maintainability

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

1. reusability

In general, the overall design style of a project is consistent. there must be several consistent styles on the page, but there are a few different modules. How to reuse CSS code as much as possible and add as little new code as possible, this is a very important point in CSS code. If CSS code is highly reusable, we may only need to write something different, which is helpful for page performance and maintainability and improving development efficiency.

2. scalability

If a function is added to the product, we should ensure that the newly added CSS Code does not affect the old CSS code and page, and add as few new code as possible to reuse the old code.

3. modifyable

If the product manager of a module thinks it is necessary to modify the style or delete it, and does not plan the corresponding CSS code, after a while, developers may no longer remember the role of this Code, and do not dare to modify or delete it. In this way, CSS code will become more and more, affecting the page performance and Code complexity.

Basic Methods for CSS code Reconstruction

We have discussed the purpose of CSS code refactoring. Now we are talking about some basic methods to achieve these goals. These methods are easy to understand and implement, you may use it without knowing it.

Methods to Improve CSS Performance

First, let's talk about how to improve the CSS performance. Based on the page loading performance and CSS code performance, we mainly summarize the following points:

1. Try to write the style in a separate css file and reference it in the head element.

Sometimes, for the convenience of graphs or quick functions, we may directly write styles on the style label of the page or directly inline them on the element. This is simple and convenient, but it is not conducive to future maintenance. Writing code into a separate css file has the following advantages:

  • Separated content and style, easy to manage and maintain

  • Reduce page size

  • Css files can be cached and reused, reducing maintenance costs

2. Do not use @ import

This method is well known. Here we will briefly mention that @ import affects the loading speed of css files.

3. Avoid using complex selectors. The fewer layers, the better.

Sometimes there are more and more project modules and more complex functions. The CSS selector we write will be nested in multiple layers and become more and more complex.

It is recommended that the nesting of selector should not exceed three layers, for example:

Can be optimized

A simple selector not only reduces the size of css files, but also improves the page loading performance. browser resolution is also more efficient. It also improves developers' development efficiency and reduces maintenance costs.

4. Streamline the style file of the page and remove unnecessary styles.

Most of the time, we merge all style files into one file, but there is a problem: many other pages reference CSS to the current page at the same time, the current page does not use them, which may cause two problems:

  • The Style File is too large, affecting the loading speed

  • The browser will perform redundant style matching, affecting the rendering time.

The correct solution is to merge the css files used on the current page based on the CSS files required on the current page.

PS: merging a style file has the following advantages: the style file will be cached by the browser. You do not need to download the Style File on other pages. This rule should be treated differently according to the scenario. If it is a large project, it should be merged into different style files. If it is a simple project, it is recommended to merge it into a file. If you cannot confirm the project scale, we recommend that you split it into different style files and merge them later.

5. Use CSS inheritance to reduce the amount of code

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

Common attributes that can be inherited include:

Color, font-size, font-family, etc.

Which cannot be inherited, for example:

Position, display, float, etc.

You can refer to the CSS Reference Manual.

Methods To improve maintainability

To improve the maintainability of CSS code, it is easy for developers to understand CSS code and modify it without disrupting the original functions. The following describes some common methods.

1. Naming and remarks

Naming is the first step to improve code readability and also an important step. Many people have this experience: naming is one of the most troublesome tasks for programmers to write code. Especially for non-English-speaking developers, it is not easy to find a proper name. Improve your naming capability and look at other people's code. The following are some naming suggestions in CSS:

Header: header

Content: content/container

End: footer

Navigation: nav

Sidebar: sidebar

Column: column

Page peripheral control overall Board Width: wrapper

Left right center

Logon entry: loginbar

Logo: logo

Advertisement: banner

Page subject: main

Hotspot: hot

News: news

Download: download

Subnavigation: subnav

Menu: menu

Sub menu: submenu

Search: search

Link: friendlink

Footer: footer

Copyright: copyright

Scroll: scroll

Content: content

Article list: list

Message: msg

Tips: tips

Topic title: title

Join: joinus

Guide: guide

Service: service

Registration: regsiter

Status: status

Vote: vote

Partner: partner

Navigation: nav

Main navigation: mainnav

Subnavigation: subnav

Top navigation: topnav

Side navigation: sidebar

Left Navigation: leftsidebar

Right navigation: rightsidebar

Menu: menu

Sub menu: submenu

Title: title

Abstract: summary

2. Extract duplicate styles

This method is easy to understand. Simply put, it is to extract the same style into a separate class and then reference it. This not only simplifies the CSS file size, but also reduces the CSS code, it is easier to reuse and maintain. For example:

The original code is as follows:

The difference between the two styles is that the text color is different. We can extract the common styles and then set different styles respectively.

Extract the public part and then reference column-title and about on the page. This makes the code more concise and easier to maintain. This example is very simple. In fact, there may be more complex situations in the project. In short, we should try to DRY and extract repetitive things as much as possible.

3. Writing Sequence

This writing sequence refers to the writing sequence of each style. below is the recommended CSS writing sequence.

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

  • Size (width, height, padding, margin)

  • Text series (font, line-height, letter-spacing, color-text-align, etc)

  • Background (background, border, etc)

  • Others (animation, transition, etc)

The writing sequence does not have to be performed according to the above recommendations, but according to your own habits, but it is best to ensure consistency between the original and original habits, or the team should have a common code specification to comply with, so it will be much easier to maintain later.

The above are some simple methods I have summarized for writing and restructuring CSS code. Of course, you do not have to stick to this. You may have different opinions and suggestions for your discussion!

CSS methodology

What is CSS methodology? To put it simply, some standards and methods for writing CSS code are proposed to improve the maintainability of CSS. They have proposed some concepts that may sound very high, but you may use these so-called CSS methodologies without knowing them. Below I will briefly introduce several common CSS methodologies.

OOCSS

OOCSS is an Object-Oriented CSS.

OOCSS has two main principles:

1. structure and style separation

We must have encountered this situation. For example, there are multiple buttons with different functions on a page. These buttons have the same shape and size, however, different features have different colors or backgrounds. If the structure and style are not separated, our CSS code may be like this.

These two or more buttons have different styles, but they have the same size style at the same time. we extract the abstract Part of the two buttons. The result is as follows:

In this way, the common style is extracted, and the buttons reference btn and primary at the same time. In addition to reducing repeated code and streamlining CSS, This method also has the advantage of reusability. To add additional buttons, you only need to write different styles and use them with btn.

(2) container and content Separation

We usually write code like this.

Such code is that the content depends on the container and there is no separate code, that is, the h3 style depends on. content container, if the same style is used elsewhere, but its container is not. content, you may want to write it again. something h3.

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

In this case, I personally recommend that you separate styles from containers, as in the previous example. But in the following case:

The style of ul and li list can be set according to our original practice. It is not necessary to set a style for li for a class, that is

In this way, the li label of the page must reference the menu-item class.

Of course, I am not sure which method is better. I like the writing of. menu li, so you can think about it on your own.

This is the two basic principles of OOCSS. Here is a brief introduction to OOCSS. If you are interested, please search for relevant information by Google.

SMACSS

What is SMACSS? its full name is Scalable and Modular Architecture for CSS. Simply put, it is a scalable and modular CSS architecture.

SMACSS divides styles into five types: Base, Layout, Module, State, and Theme. Let's simply say what each type is.

1. Base

The basic style table defines the basic style. at ordinary times, CSS is similar to reset.css, which belongs to the basic style table. In addition, I think some animations can also be classified as basic styles.

2. Layout

The layout style is used to achieve the basic layout of a webpage and build the basic skeleton of the entire webpage.

3. Module

Different Areas of the webpage have different functions. These functions are relatively independent and we can call them modules. Modules are independent and reusable. They do not depend on layout components and can be safely deleted and modified without affecting other modules.

4. State

The status style is usually used with js to indicate different states of a component or function, such as the selected menu status and the unavailable button status.

I personally think we should discuss the status style in different situations:

  • The same status style of different components is the same. For example, the selected status style of the navigation menu in the header is the same as that of the menu selected status style in the sidebar, I think this part of the State style can be classified as State

  • The uniform state of different components is different, that is, although the menus in two places are selected, they have different selected styles, this part of style should not be considered as the State type, but should be placed in the Module corresponding to its component.

5. Theme

Skin style: this is necessary for sites with replaceable skins. The structure and skin are separated and different style files are applied to different skins.

BEM

BEM is the abbreviation of Block, Element, and Modifier. These three concepts are described as follows:

  • Block: in BEM theory, a webpage is composed of blocks. For example, the header is a block, the content is a block, and the logo is also a block. A block may consist of several sub-blocks.

  • Element: an element is a part of a block and has some function. An element depends on a block. For example, in a logo, img is an element of a logo. In a menu, a menu item is an element of a menu.

  • Modifier: modifier is used to modify a block or element. It indicates the change of the block or element in appearance or behavior.

We use the BEM naming method to write the style as follows:

. Block {}

. Block-element {}

. Block-modifier {}

. Block-element-modifier {}

BEM resolves the page to block and element, and uses modifier to set the style according to different States.

My thoughts on BEM may not be in place. My views on BEM mainly consist of two points:

(1) page CSS is modularized. Each block is a module and modules are independent of each other.

(2) multi-level class naming to avoid the nested structure of Selector

CSS methodology

After reading the CSS methodology mentioned above, you will find that they have many identical ideas, such:

...

When we learn these methodologies, the most important thing is to understand their ideas. We do not have to copy its implementation form and use multiple methods in combination.

My own summary

After talking about this, let's talk about the key points of writing CSS code.

1. Before writing code: Starting from the PSD file

When we get the PSD from the designer, first of all, do not rush to write CSS code. First, analyze the entire page. The main focus is on the following:

  • The page is divided into several modules, which are common modules, such as the header and the bottom, and some menus.

  • Analyze the styles in each module and extract the public styles. Note whether the public styles are global (public throughout the page) or local (public within the module ), public styles include public state styles, such as public selected States and disabled states.

2. Start writing code

Based on the analysis of PSD files, we can start writing code. I recommend SMACSS to divide styles into different types:

  • The first step is to set up the skeleton of the page, that is, the base style and layout style.

  • The second step is to implement different modules in sequence. Here I recommend the BEM naming idea, but one or two layers of selector structure can be nested.

3. code optimization

I believe that when we finish the basic page effect, there will still be some repeated or not concise code. At this time, we are trying to optimize the code, mainly to extract repeated code, streamline the code as much as possible.

I believe you have many comments on CSS code optimization. You are welcome to exchange and discuss it!

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.