Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the recommendations for high performance and high maintainability code optimization when writing CSS

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Today, I will talk to you about the high performance and high maintainability code optimization recommendations when CSS is written, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Performance, the word is very popular nowadays, and it is also a "how to do" stage that every developer must go through after "know" and "know how to do". Performance is related to the experience of users on different devices and different network states. 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 prominent, and it is the icing on the cake if you can make the code run and parse faster on the premise of improving readability and maintainability.

First, use efficient css selectors

Simply put, css selectors that can be quickly parsed and matched by browsers are efficient selectors.

First of all, you need to know how the browser parses css

For example:

CSS Code copies content to the clipboard

.nav ul.list li div {}

Our common thinking is to first find the class nav, then find the ul that the class contains, and then find all the div in all the li of the descendants of the class list in the ul, in short, from left to right. But is this really the case? Huh? Huh? ~

The truth is the opposite! What does it mean? That is to say, instead of slowly narrowing the scope from the first, it starts with the "streaking" box of div, which is equivalent to traversing, and then finds li, and so on, well, I don't have to describe it, you should know the consumption. It's important to understand this principle, and efficient selectors mean faster matches and fewer searches. So when we define a selector, we should minimize the number of matches for the first time and minimize the number of overall matches.

The above explanations follow precisely these principles.

(1) avoid using wildcards

(2) avoid using tag selector and single attribute selector as key selector

(3) do not add a signature before the id selector

(4) try not to define too many levels in the selector, with fewer levels. At the same time, the coupling degree of css and dom structure is reduced, and the maintainability of the style is improved.

(ps: to be honest, have you ever broken all these taboos? ~)

Make a summary, as mentioned above, there are two points to know, the first point has been mentioned at the beginning, the performance of css is not prominent, especially in small projects, so, maintainability first; the second point is that although the definition of id selector, there is a unique advantage, but a page can only define a unique id, defining too much id will reduce reusability, maintenance is more difficult, so it is not recommended to use id.

Second, css-related picture processing

In today's web pages, we all know the proportion of pictures and its importance. So how to deal with the picture and how to style the picture so that users can have a better experience when they open the web page? Here are some suggestions:

(1) do not set the size of the picture

In my personal experience, there has been such a situation, I finished the page according to the design draft and handed it to the backstage to test, he suddenly came up to me and said: hi, you see, there is a situation here, I see, bad food, the picture is out of line, I remembered that I did not define the width and height of the picture (cut directly from the design draft is not necessary), and then made a mistake to define the width and height in the css style. So much so that I later took this as a note for me to do the next time I do the page. When I saw this opinion, I knew a thing or two better.

To explain, first, designers will make some pictures that exceed the required size for the beauty of the picture; second, the same picture may be used many times in different parts of the page, such as thumbnails, normal images, and large images. The problem is that if the original size of the image is different from the actual demand, there will be performance problems in the process of use. Using style scaling will bring additional calculation process of cpu, increase the rendering time of the image in the browser, and the network transmission process will take up more bandwidth and increase the download time. Therefore, it is a best practice to make a separate set of images for the required parts so that the initial page can be displayed more quickly when it loads.

(2) use css "Sprite"

It is to merge the scattered pictures into a large picture and use css to locate the background. The advantage is that the number of requests is reduced and the overall loading speed of the picture is improved.

But it also has some disadvantages:

For example, multiple pictures merged into a large picture, need accurate calculation, careful adjustment of the position, simple manual production is a very complicated thing. (fortunately, there are some tools that can help us do it.)

In addition, the maintenance process is complex, so try to keep the original position of the existing picture unchanged. If the size of the background map changes so that the original area cannot be placed, you have to give up. If you have to modify it in the original location, then the remaining picture styles need to be modified, which is a very tedious process. The newly added picture had better be at the back.

In addition, improper use can lead to performance problems, the biggest problem is memory consumption. If the production process is placed at will without any planning, the picture may become quite large, which takes up a lot of memory.

Here are some best practices:

1. Apply css sprite technology in the later stage of the project.

Because in general, in the development process, pictures will be frequently modified or changed, if sprite technology is used at this time, it will increase a lot of development costs.

2. Organize "Sprite" map reasonably.

If you want to put all the pictures on one picture, there will be something wrong, and the maintenance will not be very convenient. The organizational background map is mainly divided according to the style of the module and the background map. For example, put together as thumbnails for display, icons such as comments, likes, up and down arrows, and so on.

3. Control the size and size of the Sprite chart.

Because large images take up a lot of memory, it is recommended that the length and width be multiplied by no more than 2500, and the size is within the 200kb.

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

This principle is to prevent other irrelevant background images from appearing in the region when the background image is smaller than the element size.

5. Deal with sprite with related tools.

Third, reduce the code amount of css

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

(1) define concise css rules

Merge relevant rules and define concise attribute values

Merge rules, such as font-family, font-size, font-weight, and so on, can be merged into font. Concise attribute values, such as color values: color,#33AAFF can be simplified to # 3AF, etc.

(2) merge the same definition

There will always be some modules in the web page with high similarity, so the same part can be defined once, and different parts can be defined separately. And in css, many properties can be inherited, so you only need to define them once in the right place.

(3) delete invalid definitions

Invalid definition, will not affect the page function display, but will affect the performance of the page display, increase the amount of code, but also increase the browser parsing code time. Invalid definitions include invalid rules and invalid style attributes, which are generally introduced in the development process and cannot be judged intuitively. In this case, you can use tools, chrome's own tools can find invalid styles in css.

Other css high performance practices

(1) avoid using @ import

The new style file imported by @ import prevents the page from being downloaded in parallel, which increases the overall loading time of the file.

(2) avoid using unique styles of IE browsers: image filters and css expressions

The use of image filters will block the browser's loading and rendering when the image is loaded, and add additional memory overhead. The function of Css expression is to set the css property dynamically. The expression has not only compatibility problems, but also performance problems, such as browser size changes and window changes, which will make browsers calculate frequently and consume a lot of performance. The same effect can be achieved with javascript.

Css3 best practices

View browser support

In the process of using css3, one of the most frequently asked questions may be: what is compatibility? No way, with the development of css, it can provide a better solution for many difficult problems we have encountered before, and we can't help but wonder if we can do that. PC has the much-maligned IE series, which is much better on mobile, but some are still not so good. As a result, checking browser support is almost a must. If the features used are only decorative effects, do not affect the overall situation, then do not need to consider too many compatibility issues, if it is out of design requirements, must support all browsers, then you should pay special attention to it. Developers can choose online tools such as caniuse.com, css3 Click Chart and css contents and browser compatibility to check compatibility.

Add the necessary browser prefix

For friends who have just used css, it may be strange to see occasionally in the source code of a website, such as "- webkit-,-moz-", etc., what is this? They are prefixes added by different browser vendors.

Because browsers may only implement an early version of the standard definition when supporting css3, standard writing is not supported yet, and adding browser prefixes to the code is helpless, which makes the code more and more difficult to maintain.

However, it is not necessary to be compatible with all browsers in order to be "perfect". Generally, you can decide whether to add a prefix and several prefixes according to the market share of the browser or system version and the proportion of the target user using the browser. And I believe that with the gradual development, the system, browsers continue to upgrade, update, the need to use prefixes will be reduced.

Here comes the problem again, since we need to add the necessary prefixes, which means that sometimes it is still necessary, but if we have to add them, isn't that troublesome? The same rule has to be written three or four times, and it may be used in many places. What should I do? Don't worry, here are some countermeasures:

1. Use the tool to add the browser prefix for the css attribute

Prefixr, you can process the code at a later stage of development. It automatically adds needed prefixes and deletes unnecessary prefixes.

Autoprefixer, if you want more autonomy in the development process, you can use this tool, developers can customize the scope of browser support, it can also be used in a variety of ways, can be integrated into multiple development environments. There are also several tools available: cssFx, * css Agent*, and-prefix-free.

2. With the help of css pretreatment technology.

At present, the popular ones are sass and less. The specific method is to define a template style according to the characteristics of css3 style. The advantage is: avoid a lot of repetitive code, only need to maintain a definition.

3. Don't add browser prefixes too much

Some developers add all browser prefixes to css code in order to be compatible with all browsers, which is a negative coding method, which adds too much repetitive code, reduces browser parsing performance and increases complexity, and some prefix attributes may not be supported by browsers.

4. Add css3 standard attribute definition

What is the standard attribute definition? Without any browser prefixes, you may have noticed that many places that use css3 write standard attribute definitions at the end. Why? Because when the browser supports standard attributes, it can overwrite the definition that has been prefixed before. The standard definition of attributes in css3 is in line with the specification, and the definition with browser prefix will be gradually eliminated with the update of the browser.

Of course, it is also important to note 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 compatible handling of new features in css3

When it comes to compatibility, we will mention lower versions of IE, such as common rounded corners and transparent images, and sometimes we will downgrade them, such as filter or javascript, using box-sizing, transform, and recommended Modernizr. This framework contains many compatibility solutions for new css3 features.

No matter which kind of scheme, it will bring the loss of performance, can not be abused in disorder, it still needs to be weighed and chosen by everyone. Recommend a website for advice on how to use HTML5 more efficiently: html5please. The site divides the new features in css3 into three categories according to the way they are used:

(1) Direct use

Contains most of the new features, some features themselves will not affect compatibility, such as border-radius, media queries, etc., some need to add degradation, such as multi-background image, to set a single background image or background color as an alternative.

(2) use it cautiously

This part is mainly performance issues, such as box shadows applied to elements that occupy a large area, and significant performance problems can be caused by page scrolling or mouse hovering.

(3) avoid using

This is partly because they may only support certain browsers, such as reflection, which need to be avoided.

To sum up, there are many ways that css can be used to improve performance, but it is easy to ignore them because their impact seems to be less obvious. Moreover, many people may splash their talents arbitrarily for the sake of convenience, write whatever they want, and achieve the effect. This is also a little negative, forgetting your excellent engineer goal. Although the css rules are not difficult, and it is not easy to write them well, it is still necessary to pursue the ultimate spirit. Gentlemen, write and cherish it! ~

High maintainability css

What are the characteristics of Css?

To put it simply, the mode of use: inline, inline, outreach, import. How to style elements: element tag signatures, class names, id, various selectors, and their combinations. Therefore, it is very flexible, if you do not make any specification restrictions, it will certainly lead to css code confusion and difficult to maintain.

How to organize css code efficiently?

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

The first is to organize code files, which can be divided into two categories: general classes and business classes. Then, there is a file to reset, which is commonly named reset or default, normalize, and so on.

There is a file used to store general modules and some basic styles, often named mod, common, etc., such as page dialog box, prompt box, head, bottom, sidebar, etc., will be used in multiple pages, such as page references to improve code reuse.

Another requirement is that a file has a style compatible with older IE browsers, which has two benefits:

First, reduce the burden of non-IE browsers loading style files

Second, if you decide not to support the old IE browser in the future, you only need to modify one file, and you don't need to look for multiple files everywhere to modify them. Of course, a principle in dealing with browser compatibility is whether there are other solutions that do not have compatibility problems, and if not, put the compatibility parts in a separate file.

The rest of the 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, does not a page have to introduce a lot of files? Isn't there a lot more http requests when the page is loaded? In fact, it is not contradictory, the division of files is only for the convenience of development and maintenance, release will use tools to compress and merge multiple files into one file, so there is no need to worry about the introduction of multiple files.

What is mentioned above is the organization of the document, so the declaration of the style should also be organized according to certain rules in the document. For example, according to the level of the elements in the module, if it is the same level, then according to the position of the element in 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 think this is not enough, you can use some more advanced methods, such as less, sass, which endow css with dynamic language features, such as variables, inheritance, operations, functions, and so on.

The above is said from several major directions, and I will talk about some points below.

Display the effect using css reset Unified browser

First of all, html tags have the original style, but the problem is that in different browsers, the default style of tags is different, and some of the differences have caused trouble to the development. as early as 2004, someone developed the first reset style file, called undohtml.Css, and then there are a variety of reset programs, including a program that is "hot for a while". This program has a total of one line of code * {margin:0;padding:0;}. Reset all tags default margin, padding style, but there is a disadvantage is to increase the complexity of subsequent development, and can not effectively improve the overall development efficiency. In addition, the performance of this scheme is not good, when there are many page elements, it will affect the performance of page rendering. As a result, people are still gradually exploring better reset methods, and there are several popular reset schemes, including Reset CSS developed by Eric Meyer and YUI Reset CSS developed by Yahoo's front-end technology team. In fact, there is not a solution for all projects, so it is best to choose to refer to other people's solutions and design a set of solutions that are suitable for your own project.

The following points need to be considered:

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

(2) the differences of padding, margin and border tags in browsers are mainly caused by the default styles related to these three styles, but not the margin, padding and border of all elements that need to be reset, but should be based on the actual situation.

(3) Font settings ~, and other semantic tags all have default fonts, but the actual font size or thickness required is different from the default, so they will be reset in general projects.

(4) the typical reset of other elements is the default list item style of li, the default space between cells of table, the underscore of a link, and so on.

Define sorting for css

The logic of Css is not strong, random writing does not affect its role, if not with the help of tools to sort it will be very cumbersome, so few people will care, but sorting is still good.

For example:

1. Cleaner

2. Prevent duplicate definitions

3. Be able to see the definition clearly

4. Follow-up maintenance can quickly locate

Sort by:

1. Display and float by type, positioning, size, font, etc.

2. Arrange them in alphabetical order, the advantage is that the rules are simple

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

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

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

What is the weight, that is, the priority of many type selectors in css, the style with high priority will override the style with low priority. For the more specific rules of weight, you can refer to the data, which will not be repeated here.

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

(1) avoid using ID selector as much as possible

Two identical ID cannot be defined in a page, and the weight of the ID selector is very high. If you want to override the element style that uses the ID selector, you must add a new selector to its element, or use it! Important, the result will be more style code that cannot be reused. The best practice is to use selectors with lower weights as the base style as much as possible.

(2) reduce the level of sub-selector

It is also a process of reducing the overall weight of the sub-selector. At the same time, the fewer the levels, the less the dependence on the html structure. Another reason for excessive levels of Css is the abuse of tools such as sass and less, which I was aware of at the beginning of my use, because you can use nesting and references to define styles, which saves yourself a lot of effort, but the file will eventually have to be compiled, and we don't have to type so much code over and over again, but there will still be a lot of code generated, so While making it convenient for yourself, you should still pay special attention to reducing the selector level.

(3) use the combined css class selector

In this way, developers do not have to consider the problem of css style coverage, avoid the process of calculating selector weights, and improve the reusability of the code. the concept of combination is to separate the variable part from the stable part in a complex parent class, the stable part is divided into several simple classes, and there is no inheritance between classes, which can also reduce the dependence on html structure. The role of improving code reusability.

How is it compatible with IE browsers?

IE browsers of IE8 and below have always been a pain in the hearts of front-end developers. In order to be compatible with the extra code they add to become hack code, people often don't want to write that code. Here are some practices that are compatible with IE browsers.

(1) be familiar with the common style compatibility problems in IE browsers

One is the bug of the browser itself, and the other is not compatible with or does not support standards.

(2) separate style compatibility codes

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

Em, px or%?

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

(1) set the relative size as far as possible

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

(2) absolute size is used only when the size of the element is predictable.

For example, the design requires the use of absolute width, such as the overall width, sidebar width, the height of the head and footer of the page is fixed, in the display of pictures, videos, the appropriate fixed size will allow these multimedia elements to get the best results.

(3) use em to set the font size

Using px to set font size is not scalable, and using percentage to set font size is not in line with the habit. The best way is to use em to set font size, but with the increase of font setting levels, this method increases the cost of maintenance. For this, css3 introduces rem units, which are calculated relative to the font size of the root element, which avoids this problem. At present, except IE8 and below. It is supported by most browsers.

After reading the above, do you have any further understanding of the high performance and high maintainability code optimization recommendations when CSS is written? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report