Home  >  Article  >  Web Front-end  >  Summary of methods for optimizing and improving performance in CSS

Summary of methods for optimizing and improving performance in CSS

黄舟
黄舟Original
2017-07-27 09:37:061679browse

CSS optimization mainly focuses on four aspects:

  1. Loading performance
    There are too many best practices related to this aspect. If you just search on the Internet, you will find a lot of information. For example, don’t Use import, compression, etc., mainly from the aspects of reducing file size, reducing blocked loading, and improving concurrency. No hint can escape these general directions.

  2. Selector performance
    But the impact of selector on the overall performance is negligible, selector The inspection is more about standardization, maintainability, and robustness. Few people will focus on selector performance in actual work, but as mentioned in this GitHub share - it is better to know than not to know. good.

  3. Rendering performance
    Rendering performance is the most important focus of CSS optimization. Page rendering too junky? See if text-shadow is used extensively? Have you turned on font anti-aliasing? How is CSS animation implemented? Is GPU acceleration properly utilized? What did you use Flexible Box Model? Have you tested the impact of changing the layout strategy on render performance? If you search for CSS render performance or CSS animation performance in this regard, there will be a lot of information for reference.

  4. Maintainability, Robustness
    Is the naming reasonable? Is the structural hierarchy design robust enough? Are styles abstractly reused? Elegant CSS will not only affect later maintenance costs, but also affect loading performance and other aspects. In this regard, you can find more information about OOCSS (not that you have to use OOCSS, but that you should learn more about it) and other different CSS strategies, and learn from each other's strengths.

NO2

[CSS code reconstruction and optimization road]

Students who write CSS often realize that , as the scale of the project increases, there will be more and more CSS codes in the project. If the CSS code is not maintained in time, the number of CSS codes will continue to increase. CSS code is intertwined and complex, like a huge spider web distributed in various locations on the website. You don’t know what impact modifying this line of code will have, so if there are modifications or new features added, developers often dare not delete the old ones. The ultimate disadvantage of redundant code and adding new code safely is that there will be more and more CSS in the project, and it will eventually fall into a bottomless pit.

The purpose of CSS code reconstruction

When we write CSS code, we should not only complete the effect of page design, but also make the CSS code easy to manage and maintain. We have two main purposes for refactoring CSS code:

1. Improve code performance

2. Improve code maintainability

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, simply put, reduce the size of the CSS file size, improve the loading speed of the page, and use http caching as much as possible

2. Improve the performance of CSS code

Different CSS codes are parsed by browsers at different speeds. How to improve the speed of browser parsing CSS code is also what we need to consider

Improve the maintainability of the code

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

1. Reusability

Generally speaking, the overall design style of a project is consistent. There must be several modules with the same but slightly different styles in the page. How to use Reusing as much CSS code as possible and adding 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 some differences, which will be of great help to page performance and maintainability, and improve development efficiency.

 2. Scalability

If a certain feature is added to the product, we should ensure that the newly added CSS code will not affect the old CSS code and pages, and add as little as possible new code and reuse old code.

 3. Modifiability

If the product manager of a certain module feels that the style needs to be modified or deleted, if the corresponding CSS code is not planned, after a period of time, the development The personnel may not remember how many places this code works and dare not modify or delete it. If this continues, there will be more and more CSS codes, affecting the performance of the page and increasing the complexity of the code.

Basic methods of CSS code refactoring

I mentioned the purpose of CSS code refactoring earlier. Now let’s talk about some basic methods on how to achieve these purposes. These methods are They are some methods that are easy to understand and implement, and everyone may use them without knowing it.

Methods to improve CSS performance

First let’s talk about how to improve CSS performance. Based on the page loading performance and CSS code performance, the main summary is as follows:

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

Sometimes for convenience or to quickly get the function, we may write the style directly in the style tag of the page Or directly inline it on the element. Although this is simple and convenient, it is very detrimental to future maintenance. There are several advantages to writing the code into a separate css file:

 (1)Separation of content and style, easy to manage and maintain

 (2)Reduce page size

 (3)CSS files can be cached and reused, reducing maintenance costs

 2. Do not use @import

This method is already well known. Here is a brief mention, @import affects the loading speed of css files

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

Sometimes the project has more and more modules and the functions become more and more complex. The CSS selector we write will have multiple layers inside, making it more and more complex.

It is recommended that the nesting of selectors should not exceed three levels, for example:

.header .logo .text{}

It can be optimized to

.haeder .logo-text{}

A concise selector can not only reduce the number of css files size, improve the loading performance of the page, the browser will be more efficient when parsing, it will also improve the development efficiency of developers, and reduce maintenance costs.

 4. Streamline the style files of the page and remove unused styles

Many times, we will merge all the style files into one file, but there is a problem: many CSS of other pages They are referenced to the current page at the same time, but the current page does not use them. This situation will cause two problems:

 (1) The style file is too large, affecting the loading speed

 (2) ) The browser will perform redundant style matching, affecting rendering time.

The correct method 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 an advantage: the style file will be cached by the browser, and you don’t need to download the style file when you enter 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 one file. If the project scale cannot be confirmed, it is recommended to separate it into different style files, which will be more convenient to merge in the future.

 5. Use CSS inheritance to reduce the amount of code

We know that some CSS codes 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 a proven way to improve performance.

Common inheritable properties such as:

color, font-size, font-family, etc.

Non-inheritable properties such as:

position, display, float, etc.

Methods to improve maintainability

Improving the maintainability of CSS code simply means making it easy for developers to understand CSS code and make it easy to Modifying it will not destroy the original function. Let’s talk about some common methods.

 1. Naming and Remarks

Naming is the first step to improve code readability, and it is also an extremely important step. Many people have this experience: Naming is one of the most troublesome things for programmers when writing code. Especially for developers whose native language is not English, it is not easy to find a suitable and appropriate name. To improve your naming skills, you can look at other people's code. Here are some naming suggestions in CSS:

Header: header

Content: content/container

Footer: footer

Navigation: nav

Sidebar: sidebar

Column: column

Page peripheral control overall layout width: wrapper

Left and right center: left right center

Login bar: loginbar

Logo: logo

Advertisement: banner

Page body: main

Hotspot: hot

News: news

Download: download

Sub-navigation: subnav

Menu: menu

Sub-menu: submenu

Search: search

Friendly link: friendlink

Footer: footer

Copyright: copyright

Scroll: scroll

Content: content

Tags: tags

Article list: list

Prompt message: msg

Tips: tips

Column title: title

Join : joinus

Guide: guide

Service: service

Registration: regsiter

Status: status

Vote: vote

Partners: 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: summary

2. Extract repeated styles

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

The original code is 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;
  }

The difference between these two styles is the different text colors. We can extract their common styles and then set them separately. Its different styles

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

  提取公用的部分,然后在页面上分别引用column-title和about等,这样代码更简洁,维护起来也更方便了。这个例子非常简单,实际上项目中可能有更复杂的情况,总之就要要尽可能的DRY,尽可能的提取重复的东西。

  3、书写顺序

  这个书写顺序指的是各个样式的书写顺序,下面是推荐的CSS书写顺序

  (1)位置属性(position, top, right, z-index, display, float等)

  (2)大小(width, height, padding, margin)

  (3)文字系列(font, line-height, letter-spacing, color- text-align等)

  (4)背景(background, border等)

  (5)其他(animation, transition等)

  书写顺序不一定非得按照上面的推荐来进行,而是根据你自己的习惯,但是最好能保证前后的习惯一致的,或者团队应该有一个共同的代码规范去遵守,这样后期维护起来也会方便许多。

  以上是我个人总结的一些简单的写好和重构CSS代码的方法,大家当然不必拘泥于此,有不同的意见和建议欢迎进行交流!

 CSS方法论

  什么是CSS方法论呢?简单地说就是一些同行为了提高CSS可维护性、提出的一些编写CSS代码的规范和方法。他们提出了一些概念,这些概念可能听起来很高大上,但是实际你平时可能不知不觉也会用到这些所谓的CSS方法论。下面我简单地介绍下几个比较常见的CSS方法论。

 OOCSS

  OOCSS是(Object Oriented CSS),顾名思义就是面向对象的CSS。

  OOCSS主要有两个原则:

  1、结构和样式分离

  我们平时一定遇到过这种情况,比如一个页面存在着多个不同功能的按钮,这些按钮的形状大小都差不多,但是根据不同的功能会有不同的颜色或背景来加以区分。如果不进行结构和样式分离,我们的CSS代码可能是这样的

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

这两个或者可能更多的按钮拥有一些不同的样式,但是它们同时拥有相同的大小样式等,我们将其抽象的部分提取出来,结果如下:

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

  这样提取公用的样式出来,然后按钮同时引用btn和primary等。这种做法除了减少重复的代码精简CSS之外,还有一个好处是复用性,如果需要增加其他额外的按钮,只需要编写不同的样式,和btn配合使用即可。

  (2)容器和内容分离

  我们平时写代码一定写过这样代码

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

  这样的代码就是内容依赖于容器,没有分离的代码,也就是说h3的样式依赖于.content容器,如果其他地方要用到相同的样式,但是它的容器却不是.content,那你可能就是要再写一遍.something h3。

  所以OOCSS推荐分离容器和内容,可以修改成:

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

  关于这一点,我个人建议要分情况来看,像前面这个例子,它适合样式和容器分离。但是比如下面这种情况:

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

  这种ul,li列表的样式,我觉的就按照我们原先的做法就可以,不一定非得给一个类给li来设定样式,即

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

  这样页面的li标签需要引用menu-item类。

  当然采用哪一种方式更好我也不却确定,我自己比较喜欢.menu li的写法,大家自行思考。

  这就是OOCSS的两个基本原则,这里只是简单介绍OOCSS,各位如果有兴趣的话请自行Google查找相关资料。

  SMACSS

  SMACSS是什么呢,它的全称是Scalable and Modular Architecture forCSS。简单说就是可扩展和模块化的CSS架构。

  SMACSS将样式分成5种类型:Base,Layout,Module,State,Theme,我们简单来说说每一种类型分别指什么。

  1、Base

  基础样式表,定义了基本的样式,我们平时写CSS比如reset.css就是属于基础样式表,另外我认为清除浮动,一些动画也可以归类为基础样式。

  2、Layout

  布局样式,用于实现网页的基本布局,搭起整个网页的基本骨架。

  3、Module

  网页中不同的区域有这个不同的功能,这些功能是相对独立的,我们可以称其为模块。模块是独立的,可重用的组件,它们不依赖于布局组件,可以安全的删除修改而不影响其他模块。

  4、State

  状态样式,通常和js一起配合使用,表示某个组件或功能不同的状态,比如菜单选中状态,按钮不可用状态等。

  关于状态样式,我个人觉得要分情况进行讨论:

  (1)不同组件的同一状态的样式是一样的,比如头部的导航菜单的选中状态样式和侧栏的菜单选中状态样式是一样的,我认为这部分状态样式可以归类为State

  (2)不同组件的统一状态的样式是不一样的,即两个地方的菜单虽然都是选中状态,但是他们却又不同的选中样式,这部分样式不应该被认为是State类型,而是应该放在其组件对应的Module中。

  5、Theme

  皮肤样式,对于可更换皮肤的站点来说,这个是很有必要的,分离了结构和皮肤,根据不同的皮肤应用不同的样式文件。

  BEM

  BEM是Block,Element,Modifier的缩写。下面分别来介绍一下这三个概念:

  (1)Block:在BEM的理论中,一个网页是由block组成的,比如头部是个block,内容是block,logo也是block,一个block可能由几个子block组成。

  (2)Element:element是block的一部分,具有某种功能,element依赖于block,比如在logo中,img是logo的一个element,在菜单中,菜单项是菜单的一个element

  (3)Modifier:modifier是用来修饰block或者element的,它表示block或者element在外观或行为上的改变

  我们通过BEM命名法写样式如下:

 .block{}
  .block-element{}
  .block-modifier{}
  .block-element-modifier{}

  BEM将页面解析为block和element,然后根据不同的状态使用modifier来设置样式。

  我对BEM的思想理解可能不到位,对BEM的看法主要是由两点:

  (1)页面CSS模块化,每个block就是一个模块,模块间相互独立

  (2)多级的class命名,避免选择器的嵌套结构

 关于CSS方法论

  上面提到的这些CSS方法论,大家看了就会发现,它们其实有很多思想是相同的,比如:

  1、选择器的嵌套的优化

  2、CSS代码模块化

  3、抽象CSS代码

  …

  这些方法论,我们学习的时候,最重要的是去理解其思想,不一定非得照搬它的实现形式,多种方法结合使用。

总结

  谈了这么多,下面来说说我自己总结的写CSS代码的一些关键点。

  1、写代码之前:从PSD文件出发

  当我们拿到设计师给的PSD时,首先不要急于写CSS代码,首先对整个页面进行分析,主要关注点是下面几个:

  (1)页面分成了几个模块,哪些模块是公用的,常见的比如头部和底部,还有一些菜单栏等等

  (2)分析每一个模块都有什么样式,提取出公用的样式,注意公用样式是全局公用(整个页面公用)还是局部公用(模块内公用),公用样式包括公用的状态样式,比如公用的选中状态,禁用状态等等。

  2、开始写代码

  根据对PSD文件的分析,我们就可以开始着手写代码,我比较推荐SMACSS将样式分成不同类型的做法:

  (1)第一步是搭好页面的骨架,也就是base样式,layout样式。

  (2)第二步就是依次实现不同的模块,在这里我推荐BEM的命名思想,但是可以嵌套一到两层的选择器结构

  3、优化代码

  我相信当我们完成基本的页面效果后,还是会存在着一些重复的或者不够简洁的代码,这时候就是要去优化这些代码,主要是在提取重复代码,尽可能地精简代码。

NO3:

css性能优化的地方很多,结合以上几位大神的回答,总结如下:
1.慎重使用高性能属性:浮动、定位;
2.尽量减少页面重排、重绘
重排按照css的书写顺序:
位置:positon、top、left、z-index、float、dispay
大小:width、height、margin、padding
文字系列: font、line-height、color、letter-spacing
背景边框:background、 border
其它:anmation、transition
重绘:border、outline、background、box-shadow,能使用background-color,就尽量不要使用background;
3.去除空规则:{};
4.属性值为0时,不加单位;
5.属性值为浮动小数0.**,可以省略小数点之前的0;
6.标准化各种浏览器前缀:带浏览器前缀的在前。标准属性在后;
7.不使用@import前缀,它会影响css的加载速度;
8.充分利用css继承属性,减少代码量;
9.抽象提取公共样式,减少代码量;
10.选择器优化嵌套,尽量避免层级过深;
11.css雪碧图,同一页面相近部分的小图标,方便使用,减少页面的请求次数,但是同时图片本身会变大,使用时,优劣考虑清楚,再使用;
12.将css文件放在页面最上面

.....

The above is the detailed content of Summary of methods for optimizing and improving performance in CSS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn