Home  >  Article  >  Web Front-end  >  Summary of high performance when writing code with CSS

Summary of high performance when writing code with CSS

不言
不言Original
2018-06-12 15:56:291456browse

This article mainly introduces performance optimization when writing CSS and a summary of high-maintenance optimization suggestions, including popular discussion points such as sprite images and size settings. Friends in need can refer to

Performance, This word is very popular nowadays, and it is also a stage of "how to do it well" that every developer must go through after "knowing" and "being able to do it". Performance is about user experience on different devices and different network conditions. It is also affected by many factors. This article talks about how to achieve high performance in CSS.

High-performance css

The performance problems of Html and css themselves are not outstanding. On the premise of improving readability and maintainability, if the code can be run And the faster parsing speed is the icing on the cake.

1. Use efficient css selectors

Simply put, a css selector that can be quickly parsed and matched by the browser is an efficient selector.

First we need to know how the browser parses css

For example:

.nav ul.list li p{}

Our common thinking is to first find the nav class, Then look for the ul contained in the class, and then find all the p's in all li's that are descendants of the class list in ul. In short, from left to right. But is this the case? What? What? ~

The truth is the opposite! What does it mean? That is to say, it does not start from the first one and slowly narrow the scope, but starts from the "streaking" box p, which is equivalent to traversing, and then finds li, and so on. Well, you should know this without me describing it. consumption among them. It's important to understand this principle. Efficient selectors mean faster matching and fewer lookups. Therefore, when we define the selector, we should minimize the number of first matches and minimize the overall number of matching searches.

The above explanations exactly follow these principles

(1) Avoid using wildcards

(2) Avoid using tag selectors and single attribute selectors as key selectors

(3) Do not add tag names before the id selector

(4) Try not to define too many levels in the selector. The fewer levels, it also reduces the complexity of the CSS and DOM structures. The degree of coupling and the maintainability of the style are improved

(ps: To be honest, have you committed any of the above "taboos"?~)

To make a summary, as mentioned above, There are two points to know. The first point is mentioned at the beginning. The performance issues of CSS are not prominent, especially in small projects, so maintainability comes first. The second point is that although the id selector is defined , has the advantage of uniqueness, but a page can only define a unique ID. Defining too many IDs will reduce reusability and make maintenance more difficult, so it is not recommended to use multiple IDs.

2. CSS-related image processing

In today’s web pages, everyone knows the proportion of images and its importance. So how to handle images well and how to set styles for images so that users can have a better experience when opening web pages? Here are some opinions:

(1) Do not set the size of the picture

In my personal experience, there have been such situations. I followed the design draft After finishing the page and handing it over to the backend for testing, he suddenly came to me and said: Hi, look, something is wrong here. When I saw it, it was bad, the picture was out of place, and then I remembered that I didn’t define the width and height of the picture. (You don’t need to cut it directly from the design draft), and then you defined the width and height in the css style as if you made a mistake. So I later took this as something to pay attention to the next time I create a page. When I saw this opinion, I knew something better.

Let’s look at the explanation. First, designers will make some pictures that exceed the required size in order to make the picture beautiful. Second, the same picture may be used multiple times in different places on the page, such as thumbnails, normal Picture, big picture. Here comes the problem. If the original size of the image is different from the actual demand, there will be performance problems during use. Using style scaling will bring extra calculation process to the CPU, increase the rendering time of the image in the browser, and the network transmission process will also Take up more bandwidth and increase download time. Therefore, the best practice is to create a separate set of images for the required parts so that they can be displayed faster during the initial page load.

(2) Use css "Sprite Picture"

is to merge scattered pictures into one large picture, and use css for background positioning. The advantage is to reduce the number of requests and improve the overall loading speed of images.

But it also has some shortcomings:

For example, merging multiple pictures into a large picture requires precise calculation and careful position adjustment. Simply hand-making is a very complicated matter. (Fortunately, there are some tools that can help us do this.)

In addition, the maintenance process is complicated. Try to keep the existing pictures in their original positions. If the size of the background picture changes, the original area cannot be Place it, then you have to give up. If you have to modify it in the original position, the remaining image styles will need to be modified, which is a very cumbersome process. Newly added pictures are best placed at the end.

Also, improper use can lead to performance problems. The biggest problem is memory consumption. If you do not make any planning during the production process and place them randomly, the pictures may become quite large and occupy a lot of memory.

The following are some best practices:

1. Apply css sprite technology later in the project

Because generally during the development process, images will be modified or replaced frequently. If sprite technology is used at this time, it will increase a lot of development costs.

2. Reasonably organize the "Sprite" pictures

If you want to put all the pictures on one picture, there will be something wrong, and it will not be easy to maintain. very convenient. Organizational background images are mainly divided according to modules and background image styles. For example, thumbnails for display are placed together, and icons such as comments, likes, up and down arrows are placed together, etc.

3. Control the size and size of the "Sprite" picture

Because large-size pictures will take up a lot of memory, they must be controlled to a reasonable size. Recommended length and width The multiplication shall not exceed 2500, and the size shall be within 200kb

4. Reasonably control the distance between background image units and the position of the background image

This principle is to prevent When the size is smaller than the element size, other irrelevant background images appear in the area

5. Use relevant tools to process sprites

3. Reduce the amount of css code

An important means to improve the overall loading speed of the website is to increase the network transmission speed of code files. In addition to code compression, streamlining code is also a means.

(1) Define concise css rules

Merge related rules and define concise attribute values

Merge rules refer to things like font-family, font-size, font-weight, etc. can be combined into font. Concise attribute values, such as color value: color, #33AAFF can be simplified to #3AF, etc.

(2) Merge the same definition

There are always some modules in the web page that have high similarity, so the same part can be defined once, and different parts Define it separately. And in CSS, many properties can be inherited, so you only need to define them once in the appropriate place.

(3) Delete invalid definitions

Invalid definitions will not affect the display of page functions, but will affect the performance of page display and increase the amount of code. , also increases the time it takes for the browser to parse the code. Invalid definitions include invalid rules and invalid style attributes, which are generally introduced during the development process and cannot be judged intuitively. In this case, you can use tools, such as Chrome's own tools, to find invalid styles in CSS. .

Other css high-performance practices

(1) Avoid using @import

@import imported new style files will Prevents parallel downloads of pages, which increases the overall load time of the file.

(2) Avoid using the unique styles of IE browser: image filters and css expressions

The use of image filters will block the browser when the image is loaded. loading and rendering, and will add additional memory overhead. The function of CSS expressions is to dynamically set CSS properties. Expressions not only have compatibility issues, but also performance issues. For example, when the browser size changes or the window changes, the browser will make frequent calculations and consume a lot of performance. The same effect can be achieved with javascript.

css3 best practices

Check browser support

We get the most questions when using css3 One question might be: How is the compatibility? There is no way. With the development of CSS, it can provide a better solution to many difficult-to-solve problems we have encountered before, making us unable to help but wonder if we can do that. On the PC side, there is the much-criticized IE series, which will be much better on the mobile side, but some of it is still not very good. Therefore, checking browser support has almost become a must. If the features you use are only decorative and do not affect the overall situation, you do not need to consider too many compatibility issues. If it is due to design requirements and must support all browsers, you need to pay special attention to it. Developers can choose online tools such as caniuse.com, css3 Click Chart, css contents and browser compatibility to check compatibility.

Add the necessary browser prefix

For friends who have just started using CSS, if you occasionally see something like: "-webkit-" in the source code of a website, -moz-" Wait, you may find it strange, what is this? They correspond to the prefixes added by different browser manufacturers.

Because the browser may only implement an early version of the standard definition when supporting css3, so it does not yet support the standard writing method. Adding a browser prefix to the code is also a helpless move, which will make the code more. More difficult to maintain.

But it is not necessary to be compatible with all browsers for the sake of "perfection". Generally, you can decide whether to add it or not according to the market share of the browser or system version and the proportion of target users using the browser. Prefixes and adding several prefixes. And I believe that with the gradual development and continuous upgrades and updates of systems and browsers, the need to use prefixes will decrease.

The problem comes again. Since it is necessary to add necessary prefixes, it means that sometimes it is still necessary. If it has to be added, isn't it troublesome? The same rule needs to be written three or four times and may be used in many places. What should we do? Don’t worry, here are a few countermeasures:

1. Use tools to add browser prefixes to css attributes

Prefixr can process the code in the later stages of development. It will automatically add required prefixes and delete unnecessary prefixes.

Autoprefixer, if you want more autonomy in the development process, you can use this tool. Developers can customize the browser support range. It also has multiple ways of use and can be integrated into multiple development environments. middle. There are also several tools available: cssFx, *css Agent* and -prefix-free.

2. With the help of css preprocessing technology

Currently popular ones include sass and less. The specific method is to define a template style based on the css3 style characteristics. The advantage is: it avoids a lot of duplication of code and only needs to maintain one definition.

3. Don’t over-add browser prefixes

In order to be compatible with all browsers, some developers add the prefixes of all browsers to the css code no matter what the situation. , this is a negative encoding method that adds too much repeated code, reduces the browser's parsing performance, and increases complexity. At the same time, some prefixed attributes may not be supported by the browser.

4. Add css3 standard attribute definition

What is a standard attribute definition? There is no need for any browser prefix. You may have noticed that many places that use CSS3 will write standard attribute definitions at the end. Why? Because when the browser supports standard attributes, it can overwrite the definition with the prefix added before. The standard definition of attributes in CSS3 is the definition that conforms to the specification. The definition with the browser prefix added will gradually be eliminated as the browser is updated.

Of course, another thing to note is that some attributes currently belong to Only webkit or Only firefox, so there is no need to write standard definitions and other browser prefixes.

Do a good job of compatibility with the new features in css3

When it comes to compatibility, lower versions of IE will be mentioned, such as very common rounded corners, transparent images, etc. Sometimes we downgrade them, such as filter or javascript, using box-sizing and transform. It is recommended to use Modernizr. This framework contains many compatibility solutions for new CSS3 features.

No matter which solution is used, it will bring performance losses and cannot be abused without any rules. It still requires everyone to weigh and choose. Recommend a website with suggestions on how to use HTML5 more efficiently: html5please. The website divides the new features in CSS3 into three categories according to how they are used:

(1) Direct use of

contains most of the new features, and some features themselves are not Will affect compatibility, such as border-radius, media queries, etc. Some need to add downgrade processing, such as multiple background images, you need to set a single background image or background color as an alternative.

(2) Use with caution

This part is mainly a performance issue, such as box shadow applied to elements that occupy a large area, when the page scrolls or the mouse hovers, It will cause considerable performance problems.

(3) Avoid using

because they may only support a certain browser, such as reflection, so you need to avoid using it.

In summary, there are many ways that CSS can be used to improve performance, but we can easily ignore them because their impact does not seem to be so obvious, and many people may It’s convenient. You can use your talents freely and write whatever you want, as long as it can achieve the effect. This is also a bit negative. Have you forgotten your goal of being an excellent engineer? ! ~~Although CSS rules are not difficult, it is not easy to write them well. You still need to have some pursuit of perfection. Please write and cherish it! ~

High maintenance css

What are the characteristics of Css?

Simply speaking, usage methods: inline, embedded, external, import. How to style elements: element tag name, class name, id, various selectors, and combinations thereof. Therefore, it is very flexible. If there are no standard restrictions, it will definitely lead to confusion and difficulty in maintaining the CSS code.

How to organize css code efficiently?

Clear structure, distinct modules, and reasonable code organization structure can improve code reusability and maintainability and reduce development complexity. So how to organize it?

The first is to organize code files, which can be divided into two categories: general categories and business categories. Then, there is a file for reset. Common names are reset, default, normalize, etc.

There is a file used to store common modules and some basic styles, often named mod, common, etc., such as page dialog boxes, prompt boxes, headers, bottoms, sidebars, etc., which will be displayed on multiple pages. Used to reference each page in this way to improve code reuse.

In addition, a file is required to contain styles that are compatible with the old version of IE browser. This has two benefits:

1. Reduce the burden of loading style files for non-IE browsers

2. If you decide to no longer support the old version of IE in the future, you only need to modify one file, and there is no need to search for multiple files to modify. Of course, one principle when dealing with browser compatibility issues is whether there are other solutions that do not have compatibility issues. If not, then put the parts that need to be compatible in a separate file.

The remaining css style files are used for business modules. The style files of different modules are placed in different folders. In principle, the style files of each module should not be too large.

This may cause a problem. Doesn’t a page have to introduce many files? Aren't there a lot more http requests when the page is loading? In fact, there is no contradiction. The division of files is only to facilitate development and maintenance. When publishing, tools will be used to compress and merge multiple files into one file, so there is no need to worry about introducing multiple files.

The above is about the organization of files, so style statements must also be organized in files according to certain rules. For example, according to the level of the elements in the module, if they are at the same level, then according to the position of the element on the page, from top to bottom, or from left to right. If there are multiple elements sharing the same declaration, the common style should be declared first. If you feel that this is not enough, you can use some more advanced methods, such as less and sass, which give CSS dynamic language features, such as variables, inheritance, operations, functions, etc.

The above is discussed from several general directions. Let’s talk about certain points below

Use css reset to unify the browser display effect

First of all, html tags have original styles, but the problem is that in different browsers, the default styles of tags are different. Some of these differences have caused trouble for development. As early as 2004, someone developed The first reset style file was created, called undohtml.Css. Subsequently, there were a variety of reset plans, one of which was "hot for a while". This plan has a total of one line of code *{margin: 0; padding: 0;} . The default margin and padding styles of all tags have been reset. However, one drawback is that it increases the complexity of subsequent development and cannot effectively improve the overall development efficiency. In addition, the performance of this solution is also poor, which will affect the performance of page rendering when there are many page elements. Therefore, people are gradually exploring better reset methods. There are currently many popular reset solutions, including Reset CSS developed by Eric Meyer and YUI Reset CSS developed by Yahoo's front-end technology team. In fact, there is no one solution that is suitable for all projects, so it is best to refer to other people's solutions and then design a solution that suits your own project.

The following points need to be considered:

(1) HTML5 new tags need to reset their display styles because their default display styles are not defined in earlier versions of IE.

(2) The differences between padding, margin, and border tags in browsers are mainly caused by the default styles related to these three styles, but it does not require resetting the margin, padding, and border of all elements. It should be based on the actual situation.

(3) Font settings 4a249f0d628e2318394fd9b75b4636b1~4e9ee319e0fa4abc21ff286eeb145ecc, 8e99a69fbe029cd4e2b854e244eab143, 907fae80ddef53131f3292ee4f81644b and other semantic tags have default fonts, but the actual font size or thickness required is They are different from the default, so they will be reset in general projects.

(4) Style reset of other elements. Typical examples include the default list item style of li, the default space between cells of the table, the underline of a link, etc.

Defining sorting for css

Css is not very logical, and random writing does not affect its function. Sorting it without the help of tools will be very cumbersome. So, few people will care, but there are still benefits to sorting.

For example:

1. Cleaner

2. Prevent duplicate definitions

3. Ability to clearly view definitions

4. Follow-up Maintenance can quickly locate

Sorting method:

1. By type, such as display and floating, positioning, size, font, etc.

2. Sort by letter in alphabetical order, The advantage is that the rules are simple

3. Arrange according to the defined length and the character length defined by the style

Each has its own advantages and disadvantages. In practical applications, the first one is recommended. However, it is difficult for front-end engineers to do this alone during the writing process. You can write in the most efficient way during the writing process, and use tools to sort the css when submitting the code. It not only improves efficiency, but also facilitates subsequent code reading and maintenance. One free tool is CSScomb.

Make reasonable use of the weight of css to improve code reusability

What is weight, that is, the priority of many types of selectors in css. Styles with higher priority will override the priority. Low level style. For more specific rules of weight, you can check the information and will not go into details here.

Here is how to define the appropriate selector according to the weight of the selector:

(1) Try not to use the ID selector

on one page It is not allowed to define two identical IDs in , and the ID selector has a high weight. If you want to override the element style that uses the ID selector, you must add a new selector to its element, or use! important, the result will be more style code that cannot be reused. Best practice is to use lower weight selectors as the base style whenever possible.

(2) Reduce the level of sub-selectors

is also the process of reducing the overall weight of the sub-selector. At the same time, the fewer levels, the lower the dependence on the html structure. Another reason for too many levels of CSS is the abuse of tools such as sass and less. This is also a problem I was aware of when I first started using it, because you can use nesting and references to define styles, which provides I saved a lot of effort, but the file still has to be compiled in the end. We don't have to type so much code repeatedly, but the generated code will still be a lot. Therefore, while it is convenient for yourself, you still have to pay special attention to reducing the selector level.

(3) Use combined css class selectors

Using this method, developers do not need to consider the issue of css style overrides and avoid calculating selectors The weighting process also improves the reusability of the code. The concept of combination is to separate the variable part and the stable part in a complex parent class. The stable part is used as the main class, and the variable part is divided into several simple classes. There is no inheritance between classes, which can also reduce dependence on HTML structure and improve code reusability.

How to be compatible with IE browser?

IE8 and below versions of IE browser have always been a pain in the hearts of front-end developers. The extra code added to be compatible with them becomes hack code, and people often don't want to write that code. The following are some practical methods for compatibility with IE browsers.

(1) Be familiar with common style compatibility issues in IE browsers

One type is the bug of the browser itself, and the other type is incompatible with the standard or not yet Support standards.

(2) Separate style compatible code

Organize code files according to different versions of the browser, and then use judgment statements to load on demand

em, px or %?

The reason for talking about this topic is that nowadays, page functions are becoming more and more, and there are more and more devices used to access the page. The layout of the page is a quite challenging thing, and the page The size and font of the elements, the size of the pictures, etc. are also closely related to the layout. In view of this, front-end development began to pay attention to how to improve page layout. The core idea is to set the size and font size of page elements to relative values. Font relative units include: em, ex, ch, rem. There is no need to go into details, there is more information to explain. Here are some best practices:

(1) Try to set relative sizes

The so-called setting of relative sizes does not mean that the overall layout of the page is adaptive. , the overall size can be a fixed size or an adaptive size, depending on the design of the page.

(2) Only use absolute sizes when the size of the element is predictable

For example, the design requires the use of absolute widths, such as overall width and sidebar width. , the height of the page header and footer is fixed, etc. When displaying pictures and videos, appropriate fixed sizes will achieve the best results for the display of these multimedia elements.

(3) Use em to set the font size

The scalability of using px to set the font size is not good, and using percentage to set the font size is also unconventional, best The method is to use em to set the font size, but as the levels of font settings increase, this method increases the cost of maintenance. For this, CSS3 introduces the rem unit, which is calculated relative to the font size of the root element, thus avoiding This problem is currently supported by most browsers except IE8 and below.

Many things in this article are just mentioned. I hope it can provide some guidance and help to some novices. Everyone will have some feelings, experiences, lessons, etc. in their own gradual practice. I believe it will be very beneficial to often summarize and put them into their next practice. Let's make it together! ~

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Methods to improve css performance

The above is the detailed content of Summary of high performance when writing code with 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