Original address: luopq.com/2016/01/05/…

Students who write CSS often realize that with the increase of the size of the project, the CSS code in the project will be more and more. If the CSS code is not maintained in time, the CSS code will be more and more. CSS code intertwined, like a huge spider web distribution in each site location, you don’t know what effect will change the line of code, so if you have to modify or add new functionality, developers often dare not to delete the old redundant code, and insurance to increase the new code, the disadvantages of the final project is the CSS will be more and more, eventually into a bottomless pit.

The purpose of CSS code refactoring

When we write CSS code, not only to complete the effect of the page design, but also to make CSS code easy to manage and maintain. We have two main goals for CSS refactoring: 1) to improve code performance and 2) to improve code maintainability

Improving code performance

There are two main ways to improve CSS code performance: 1, improve the page loading performance to improve the page loading performance, in short, is to reduce the size of the CSS file, improve the page loading speed, can make use of HTTP cache 2, improve the CSS code performance different CSS code, browser parsing speed is not the same. How can we speed up the browser’s ability to parse CSS code

Improve code maintainability

To improve the maintainability of the CSS code is mainly embodied in the following points: 1, reusable In general, a project’s overall design style is consistent, the page must have a few style is consistent but slightly different modules, how to reuse as much as possible the CSS code, as little as possible to increase the new code, this is very important in the CSS code. If CSS code is highly reusable, we may just need to write a few different things, which will greatly improve page performance and maintainability, and improve development efficiency.

2. Extensibility If a feature is added to the product, we should ensure that the new CSS code does not affect the old CSS code and pages, and reuse the old code by adding as little new code as possible.

3, modifiability If a module product managers think to change the style, or to delete it, if there is no plan corresponding CSS code, after a period of time, the developer may have not remember this code a few places, dare not to modify, or delete it, so the CSS code is also more and more, affect the performance of the page, It also contributes to code complexity.

Basic methods for CSS code refactoring

Now that I’ve talked about the goals of CSS code refactoring, I’m going to talk about some basic ways to achieve those goals. They’re easy to understand, easy to implement, and you might be using them unconsciously.

Methods to improve CSS performance

First talk about how to improve CSS performance, according to the page load 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 convenience or quick access to the function, we may directly write the style in the page style tag or directly inline on the element, although simple and convenient, but very bad for future maintenance. Writing code as a separate CSS file has several advantages: (1) content and style separation, easy to manage and maintain, (2) reduced page size, and (3) CSS files can be cached and reused, reducing maintenance costs

2. It is well known that @import is not used, but it affects the loading speed of CSS files

3. Avoid complex selectors, as few layers are as good as possible. Sometimes as projects become more and more complex with more modules, we write CSS selectors with more and more complex layers inside them. It is recommended that the nesting of selectors should not exceed three layers, for example:


.header .logo .text{}
Copy the code

Can be optimized into


.haeder .logo-text{}
Copy the code

Simple selectors not only reduce CSS file sizes, improve page loading performance, but also make browser parsing more efficient, improve developer productivity and reduce maintenance costs.

Most of the time, we will combine all the style files into one file, but there is a problem with this: the CSS of many other pages references the current page, and the current page does not use them. This situation causes two problems: (1) The style file is too large, affecting the loading speed. (2) the browser will make redundant 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 single file has one advantage: the style file is cached by the browser, so you don’t have to download it when you go to other pages. This rule should vary depending on the scenario. If it is a large project, it should be combined into different style files. If it is a simple project, it is recommended to combine into one file. If you cannot confirm the size of the project, it is recommended to separate it into different style files so that it can be easily combined later.

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 also an effective way to improve performance. Common inherited properties such as color, font-size, font-family, etc. cannot be inherited, such as position, display, float, etc

Check out the CSS reference manual

Ways to improve maintainability

To improve the maintainability of CSS code, simply put, is to make it easy for developers to understand CSS code, easy to modify it, and not destroy the original function. Here are some common tools. Naming and Remarks Naming is the first and most important step in improving code readability. As many of us will attest, naming is one of the most frustrating aspects of writing code, especially for developers whose first language is not English. Improve your naming skills by looking at other people’s code. Here are some naming suggestions for CSS:

Header: Header content: Content/Container End: Footer Navigation: Nav Sidebar: sidebar Column Page Peripheral control Overall layout width: Wrapper Left right Center: Left Right Center Login bar: Loginbar logo: Logo Advertising: banner Page main: main Hot: Hot News: News Download: Download Sub-navigation: Subnav menu: Menu Sub-menu: submenu search: Search Friendlink footer: Footer copyright: Copyright Scroll: Content Tags Article list: MSG Tips column title: Join: Joinus Guide: Guide Services: Service Register: Regsiter Status: Status Vote: Vote Partner navigation: Nav Main Navigation: MainNav Sub-navigation: SubNAV Top navigation: TopNAV Side navigation: sidebar Left navigation: Leftsidebar right navigation: Rightsidebar Menu: Menu Submenu: Submenu Title: Title Summary: SummaryCopy the code

2, extract repeated styles this method is easy to understand, simply say is to extract the same style into a separate class and then reference, this can not only simplify the CSS file size, and CSS code less, easier to reuse and maintenance. For example: The original code looks like 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; 
}Copy the code

The difference between these two styles is the color of the text. We can extract the common style and then set the different styles separately

.column-title{
    margin: 0 auto 6rem; text-align: center; letter-spacing: 4px; font-size: 2rem; 
}
.about{
    color: #333;
}
.achieve{
    color:#fff;
}Copy the code

Extracting the common parts and then referring to column-title, about, and so on on the page makes the code simpler and easier to maintain. This example is very simple, and in fact there may be more complex cases in the project, but just try to be as DRY as possible, and try to extract as many repetitions as possible.

3. Writing Order This writing order refers to the writing order of each style. The following is the recommended CSS writing order (1) Position properties (position, top, right, Z-index, display, float, etc.) (2) Size (width, height, padding, etc.) Margin (3) Text series (font, line-height, letter-spacing, color-text-align, etc.) (4) background (background, border, etc.) (5) other (animation, animation, etc.) You don’t have to follow the recommended order, you have to follow your own habits, but it’s best to make sure that the habits are consistent, or that the team should have a common code specification to follow, which will be easier to maintain later.

Above is my personal summary of some simple writing and refactoring CSS code methods, of course, we do not need to stick to this, there are different opinions and suggestions welcome to exchange!

CSS methodology

What is the CSS methodology? To put it simply, it is the specification and method of writing CSS code proposed by some peers to improve the maintainability of CSS. They come up with a few concepts that may sound fancy, but you’re probably using these so-called CSS methodologies on a regular basis. Let me briefly introduce some of the more common CSS methodologies.

OOCSS

OOCSS is Object Oriented CSS, as the name implies. There are two main principles of OOCSS: 1, structure and style separation we often encounter this situation, such as a page has multiple buttons with different functions, the shape and size of these buttons are similar, but according to different functions will have different colors or backgrounds to distinguish them. Without the separation of structure and style, our CSS code might look 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;
}Copy the code

These two or more buttons have some different styles, but they both have the same size style, etc. We extract the abstract part of them, and the result is as follows:

.btn{
    width:100px;
    height:50px;
    padding:5px 3px;
}
.primary{
    background:red;
    color:#fff;
}
.delete{
    background:red;
    color:#fff;
}Copy the code

This extracts the common style, and the button references both BTN and primary. One of the benefits of this approach, besides reducing the amount of repetitive code simplification CSS, is reusability. If you need to add additional buttons, you can just write different styles and use them with BTN.

(2) Container and content separation we usually write code must have written such code

.content h3{
    font-size:20px;
    color:#333;
}Copy the code

So this code is content dependent on the container, there’s no separate code, so the style of H3 depends on the dot content container, so if you’re going to use the same style somewhere else, but its container isn’t dot content, then you’re probably going to have to write something h3 again. So OOCSS recommends separating containers and content, which can be modified to:

.title{
    font-size:20px;
    color:#333;
}Copy the code

I personally recommend this on a case-by-case basis, as in the previous example, which is suitable for style and container separation. But here’s the case:

.menu li{
    font-size:12px;
}Copy the code

This ul, LI list style, I think we can just do what we did before, we don’t have to style a class for LI, that is

.menu-item{
    font-size:12px;
}Copy the code

So the li tag of the page needs to reference the menu-item class. Of course, I am not sure which way is better, I prefer the writing method of menu Li, we can think by ourselves. These are the two basic principles of OOCSS. This is just a brief introduction to OOCSS. If you are interested, please do your own Google search.

SMACSS

What is SMACSS? It stands for Scalable and Modular Architecture for CSS. In short, it is the extensible and modular CSS architecture. SMACSS divides styles into five types: Base, Layout, Module, State, and Theme. Let’s briefly describe what each type refers to. 1. Base style sheet, which defines the basic style, we usually write CSS such as reset. CSS is a Base style sheet, and I think clear float, some animation can also be classified as Base style.

2, Layout, used to achieve the basic Layout of the web page, build up the basic skeleton of the entire web page.

Different areas in the web page have different functions, which are relatively independent, we can call them modules. Modules are independent, reusable components that do not depend on layout components and can be removed and modified safely without affecting other modules.

4. The State style, usually used in conjunction with JS, represents different states of a component or function, such as menu selection, button unavailable, etc. In terms of state styles, I personally feel that we need to discuss them on a case-by-case basis: (1) the State of the different components of the same style is the same, such as the head of the navigation menu selected style and style of the sidebar menu selected is the same, I think this part of the State style can be classified as a State (2) the State of the unity of the different components of the style is different, the two places menu is selected, However, they have different selected styles, which should not be considered State, but should be placed in the corresponding Module of their component.

5. Theme skin styles. This is necessary for a replaceable skin site, separating structure and skin, and applying different style files for different skins.

BEM

BEM stands for Block, Element, Modifier. (1) Block: In THE theory of BEM, a web page is composed of blocks. For example, the head is a Block, the content is a Block, and the logo is also a Block. A Block may be composed of several sub-blocks. (2) Element: Element is part of a block and has a function that depends on the block. For example, in a logo, img is an Element of the logo, and in a menu, the menu item is an Element of the menu. Modifier is used to modify a block or element. It changes the appearance or behavior of a block or element. .block{}.block-element{}.block-modifier{}. Block-element-modifier {} BEM parses the page into block and Element, then uses the modifier to set the style for each state. My understanding of THE idea of BEM may not be in place, the view of BEM mainly consists of two points: (1) page CSS modularization, each block is a module, the modules are independent of each other (2) multi-level class naming, avoid the nested structure of the selector

About the CSS Methodology

These CSS methodologies mentioned above, you will find that they actually have a lot of ideas in common, such as: 1, the nested optimization of the selector 2, CSS code modularization 3, abstract CSS code… When we study these methodologies, the most important thing is to understand their ideas, not necessarily to copy their implementation form, a combination of methods.

My own way of summarizing

With that said, here are some of the key points I’ve made about writing CSS code. 1, before writing the code: start from the PSD file when we get the designer to the PSD, first of all do not rush to write CSS code, first of all to analyze the whole page, the main focus is the following: (1) page is divided into several modules, which modules are common, such as the head and bottom of the common, and some of the menu bar, etc. (2) analysis of each module is what style, extract the common style, pay attention to the common style is a global public utility (the entire page) or local public (module utilities), the state of the public styles including style, Public selected states, disabled states, and so on. Based on the analysis of PSD files, we can start to write code. I recommend SMACSS to divide styles into different types: (1) The first step is to build a good skeleton of the page, that is, the base style, layout style. (2) the second step is, in turn, to achieve different modules, here I recommend the BEM named thought, but can be nested one or two layers of selector 3 structure, optimize the code I believe when we complete the basic effect of page, there will still be some repetitive or not enough concise code, this time is to optimize the code, mainly in the extraction of duplicate code, Keep your code as lean as possible.

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