In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "what are the methods of CSS code refactoring and optimization", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what are the methods of CSS code refactoring and optimization"?
The purpose of CSS code refactoring
When we write CSS code, we should not only complete the effect of page design, but also make CSS code easy to manage and maintain. We have two main purposes for refactoring CSS code:
1. Improve code performance
2. Improve the maintainability of the code
Improve code performance
There are two main points to improve the performance of CSS code:
1. Improve the loading performance of the page
To improve the loading performance of the page, to put it simply, it is to reduce the size of the CSS file, improve the loading speed of the page, and make use of the http cache as much as possible.
2. Improve the performance of CSS code
The speed of browser parsing is also different for different CSS code, and how to improve the speed of browser parsing CSS code is also something we need to consider.
Improve the maintainability of the 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, and there must be several modules with the same style but slightly different styles on the page. How to reuse as much CSS code as possible and add as little new code as possible is a very important point in CSS code. If the reusability of CSS code is high, we may only need to write something different, which is of great help to page performance and maintainability, and to improve development efficiency.
2. Scalability
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 add as little new code as possible and reuse the old code.
3. Can be modified
If a module product manager feels to modify the style, or to delete it, if the corresponding CSS code is not planned, after a period of time, the developer may not remember how many places this code has played, and dare not modify or delete it, so there will be more and more CSS code, affecting the performance of the page, but also causing the complexity of the code.
Basic methods of CSS Code refactoring
Previously mentioned the purpose of CSS code refactoring, now let's talk about some basic methods to achieve these goals, these methods are easy to understand, easy to implement, and you may be using it unwittingly.
Ways to improve the performance of CSS
First of all, let's talk about how to improve the performance of CSS. According to the loading performance of the page and the performance of CSS code, the main points are as follows:
1. Try to write the style in a separate css file and reference it in the head element
Sometimes for the sake of convenience or quick completion of the function, we may write the style directly on the style tag of the page or inline the element directly, which is simple and convenient, but it is not conducive to future maintenance. There are several advantages to writing code as a separate css file:
(1) content and style are separated and easy to manage and maintain
(2) reduce the page size
(3) css files can be cached and reused, and the maintenance cost is reduced.
2. Do not use @ import
This method is already well known. It is briefly mentioned here 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 modules in the project, and the functions become more and more complex. The CSS selector we write will cover multiple layers and become more and more complex.
It is recommended that the nesting of selectors should not exceed three layers, such as:
Header.logo.text {}
Can be optimized to
Haeder.logo-text {}
Simple selector can not only reduce css file size, improve page loading performance, browser parsing will also be more efficient, but also improve developers' development efficiency and reduce maintenance costs.
4. Simplify the style file of the page and get rid of the unused styles
In many cases, we merge all the style files into one file, but there is a problem: the CSS of many other pages are referenced to the current page at the same time, and the current page does not use them, which creates two problems:
(1) the style file is too large, which affects the loading speed
(2) the browser will make redundant style matching, which will affect 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 one file has one advantage: style files are cached by browsers, so you don't have to download them when entering other page style files. This rule should be treated differently according to the scene, 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 into a single file. If you cannot confirm the size of the project, it is recommended to separate it into different style files, and it is more convenient to merge in the future.
5. Reduce the amount of code by using CSS inheritance
We know that part of the CSS code can be inherited, and if the parent element has already set the style, the child element does not need to set the style, which is also an effective way to improve performance.
Common inheritable properties such as:
Color,font-size,font-family, wait.
Something that cannot be inherited, such as:
Position,display,float et al.
You can check the CSS reference manual.
Ways to improve maintainability
To improve the maintainability of CSS code, simply to make it easy for developers to understand CSS code, easy to modify it, will not destroy the original functionality. Let's talk about some common methods.
1. Naming and remarks
Naming is the first and most important step in improving the readability of the code. Many people have the experience that naming is one of the biggest headaches for programmers in writing code, especially for developers whose native language is not English, it is not easy to find a suitable name. To improve your own naming ability, you can look at other people's code more. Here are some naming-related suggestions in CSS:
Head: header
Content: content/container
Tail: footer
Navigation: nav
Sidebar: sidebar
Column: column
The overall width of the page periphery control: wrapper
Left and right center: left right center
Login bar: loginbar
Logo: logo
Advertisement: banner
Page body: main
Hot spot: hot
News: news
Download: download
Subnavigation: subnav
Menu: menu
Submenu: submenu
Search: search
Link: friendlink
Footer: footer
Copyright: copyright
Scroll: scroll
Content: content
Tag: tags
List of articles: list
Tip: msg
Tip: tips
Column title: title
Join: joinus
Guide: guide
Service: service
Registration: regsiter
Status: status
Voting: vote
Partner: partner
Navigation: nav
Main navigation: mainnav
Subnavigation: subnav
Top navigation: topnav
Edge navigation: sidebar
Left navigation: leftsidebar
Navigation on the right: rightsidebar
Menu: menu
Submenu: submenu
Title: title
Summary: summary
2. Extract repetitive styles
This method is easy to understand, simply by extracting the same style into a separate class re-reference, which not only simplifies the CSS file size, but also reduces CSS code, making it easier to reuse and maintain. For example, the following example:
The original code looks like this:
CSS Code copies content to the clipboard
. 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 lies in the color of the text. We can extract their common styles and then set them separately.
CSS Code copies content to the clipboard
. column-title {
Margin: 0 auto 6remt; text-align: center; letter-spacing: 4px; font-size: 2rem
}
.about {
Color: # 333
}
.achieve {
Color:#fff
}
Extract the common parts, and then reference column-title, about, etc., respectively on the page, so that the code is more concise and easier to maintain. This example is very simple. In fact, there may be more complex situations in the project. In short, it is necessary to DRY as much as possible and extract duplicates as much 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) location 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 habits are consistent, or the team should have a common code specification to follow. This will be much easier to maintain later.
The above is my personal summary of some simple ways to write and ReFactor CSS code, of course, we do not have to adhere to this, there are different opinions and suggestions are welcome to exchange!
CSS methodology
What is the CSS methodology? To put it simply, it is some specifications and methods for writing CSS code put forward by some colleagues in order to improve the maintainability of CSS. They have come up with some concepts that may sound high-end, but in fact you may also unwittingly use these so-called CSS methodologies. Let me briefly introduce some of the more common CSS methodologies.
OOCSS
OOCSS is (Object Oriented CSS), which, as its name implies, is object-oriented CSS.
OOCSS has two main principles:
1. Separation of structure and style
We must have encountered this situation, for example, there are many buttons with different functions on a page, all of which are of the same shape and size, but can be distinguished by different colors or backgrounds according to different functions. Without the separation of structure and style, our CSS code might look like this
CSS Code copies content to the clipboard
. 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 more buttons have some different styles, but they also have the same size and style, and so on. We extract the abstract part of them, and the result is as follows:
CSS Code copies content to the clipboard
.btn {width:100px;height:50px;padding:5px 3px;}
.primary {background:red;color:#fff;}
.delete {background:red;color:#fff;}
This extracts the common style, and then the button references both btn, primary, and so on. In addition to reducing repetitive code and streamlining CSS, another benefit of this approach is reusability. If you need to add other additional buttons, you just need to write different styles and use them with btn.
(2) Separation of container and content
We must have written code like this before.
CSS Code copies content to the clipboard
.content h4 {
Font-size:20px
Color:#333
}
This kind of code is that the content depends on the container, and there is no separate code, that is to say, the style of h4 depends on the .content container. If the same style is used elsewhere, but its container is not .content, then you may want to write .content h4 again.
Therefore, OOCSS recommends separating the container from the content, which can be modified to:
CSS Code copies content to the clipboard
.title {
Font-size:20px
Color:#333
}
On this point, I personally suggest that on a case-by-case basis, like the previous example, it is suitable for style and container separation. But for example, this is the case:
CSS Code copies content to the clipboard
.menu li {
Font-size:12px
}
The style of this ul,li list, I think, is fine according to our previous practice, and it is not necessary to set the style for a class to li, that is,
CSS Code copies content to the clipboard
. menu-item {
Font-size:12px
}
So the li tag of the page needs to refer to the menu-item class.
Of course, I am not sure which way is better. I prefer the way menu li is written, and everyone thinks for themselves.
These are the two basic principles of OOCSS, 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. To put it simply, it is an extensible and modular CSS architecture.
SMACSS divides styles into five types: Base,Layout,Module,State,Theme, and let's briefly talk about what each type refers to.
1 、 Base
Basic style sheet, defines the basic style, we usually write CSS such as reset.css belongs to the basic style sheet, in addition, I think to clear the float, some animation can also be classified as the basic style.
2 、 Layout
The layout style is used to realize the basic layout of the web page and build up the basic skeleton of the whole web page.
3 、 Module
Different areas of the web page have this different function, these functions are relatively independent, we can call them modules. Modules are independent, reusable components that do not depend on layout components and can safely delete modifications without affecting other modules.
4 、 State
State style, usually used with js, indicates a state in which a component or function is different, such as a menu selected state, a button unavailable state, and so on.
With regard to the status style, I personally think we should discuss it on a case-by-case basis:
(1) the same state style of different components is the same. For example, the selected state style of the navigation menu in the head is the same as that of the sidebar. I think this part of the state style can be classified as State.
(2) the style of the unified state of different components is different, that is, although the menus of the two places are selected, they have different selected styles, 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, which is necessary for sites with replaceable skin, separates the structure from the skin and applies different style files according to different skins.
BEM
BEM is the abbreviation of Block,Element,Modifier. Let's introduce these three concepts respectively:
(1) Block: in the theory of BEM, a web page is composed of block, for example, the head is a block, the content is block,logo and block, and a block may be composed of several sub-block.
(2) Element:element is a part of block and has certain functions. Element depends on block. For example, in logo, img is an element of logo, and in menus, menu items are an element of menus.
(3) Modifier:modifier is used to modify block or element. It represents a change in the appearance or behavior of block or element.
We write the style through the BEM naming method as follows:
CSS Code copies content to the clipboard
.block {}
. block-element {}
. block-modifier {}
.block-element-modifier {}
BEM parses the page into block and element, and then uses modifier to style it according to different states.
I may not have a good understanding of BEM, and my views on BEM are mainly based on two points:
(1) Page CSS is modular. Each block is a module, and the modules are independent of each other.
(2) Multi-level class naming to avoid the nested structure of selectors
On CSS Methodology
If you look at the CSS methodology mentioned above, you will find that they actually have many ideas in common, such as:
1. Optimization of selector nesting
2. CSS code modularization
3. Abstract CSS code
...
When we learn these methodologies, the most important thing is to understand their ideas, it is not necessary to copy its implementation form, a variety of methods are used together.
I summed up the method myself.
Having talked about so much, let's talk about some of the key points I have summed up for writing CSS code.
1. Before writing the code: start from the PSD file
When we get the PSD from the designer, first of all, don't rush to write the CSS code, first analyze the whole page, the main concerns are the following:
(1) the page is divided into several modules, which modules are common, such as head and bottom, some menu bars and so on.
(2) analyze what style each module has, extract the common style, pay attention to whether the common style is global (the whole page is common) or local common (common within the module), the common style includes the common state style, such as the common selected state, disabled state, and so on.
2. Start writing code
Based on the analysis of the PSD file, we can start writing code, and I recommend SMACSS's practice of dividing styles into different types:
(1) the first step is to build the skeleton of the page, that is, base style, layout style.
(2) the second step is to implement different modules in turn. Here I recommend the naming idea of BEM, but one or two layer selector structures can be nested.
3. Optimize the code
I believe that when we finish the basic page effect, there will still be some repetitive or not concise code, which is to optimize the code, mainly to extract repetitive code and simplify the code as much as possible.
At this point, I believe you have a deeper understanding of "what are the methods of CSS code refactoring and optimization?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.