High performance summarization of CSS when writing code

Source: Internet
Author: User
Tags unique id
This article mainly introduces the performance optimization of CSS writing and the recommendation summary of High Maintenance optimization, including the hot discussion points such as Sprite chart and size setting, the friends who need can refer to the following

Performance, the word is now fired very hot, but also every developer, from the "Know", "will do" after a "how to do" stage. Performance is about the user's experience in different devices and different network states. is also influenced by many factors. This article says how to achieve high performance in CSS.

High-performance CSS

The performance problems of HTML and CSS itself are not obvious, and it is icing on the cake if you can make your code run and parse faster, while improving readability and maintainability.

First, using the efficient CSS Selector

In short, a CSS selector that can be quickly parsed and matched by a browser is an efficient selector.

The first thing to know is how the browser parses the CSS

As an example:

. Nav ul.list Li p{}

Our common thinking is, first to find the Nav class, and then find the class contains the UL, and then find the UL class for the list of all Li in the descendants of all p, in short, is from left to right. But is it true? Do you? Do you? ~

The truth is the opposite! What does it mean? That is, it is not from the first start to slowly narrow the range, but from the "Naked Ben" in the box to start, the equivalent of traversing, and then find Li, and so on, well, I do not describe you should know the consumption of this. Understanding this principle is important, and efficient selectors mean faster matching and fewer lookups. So when we define selectors, we should make the first match the fewest number, and make the whole match find the least number of times.

These explanations follow some of these principles

(1) Avoid using wildcard characters

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

(3) Do not spike the signature before the ID selector

(4) Try not to define too many levels in the selector, the less the hierarchy, but also reduce the degree of coupling between CSS and DOM structure, improve the maintainability of the style

PS: Honestly, are you guilty of these "taboos"? ~

To make a summary, said above, there are two points need to know, the 1th in the beginning has been mentioned, CSS performance problem performance is not outstanding, especially in small projects, so, maintainability is first; the 2nd is that while defining the ID selector, there is a unique advantage, but a page can only define a unique ID. Defining too many IDs can reduce reusability and make maintenance more difficult, so it is not recommended to use multiple IDs.

Second, CSS-related image processing

Today's Web page, the proportion of the picture and its importance is known to everyone. So how do you handle good pictures and how to style them so that users can experience better when they open a page? Here are a few ideas:

(1) Do not set the size of the picture

In my personal experience, there have been such circumstances, I finished the page in accordance with the design manuscript, to the background to test, he suddenly ran over to me and said: Hi, you see, here out of the situation, I see, bad food, pictures out of the way, I think not to the picture definition width (directly from the design of the manuscript cut also do not need), And then you make a mistake. Defines the width height in the CSS style. So that later I take this as the next time to do the page time considerations. When I see this opinion, I know one or two more.

To explain, first, the designer for the beautiful picture, will make some beyond the requirements of the size of the picture; second, the same picture may be used multiple times in different places of the page, such as thumbnails, normal figures, large images. The problem is, if the original size of the picture and the actual demand, there will be a performance problem in the process, the use of style scaling will bring additional CPU calculation process, increase the picture in the browser rendering time, the network transmission process will occupy more bandwidth, increase the download time. As a result, the best practice is to make a separate set of images for the part you want, and the initial page load will show up faster.

(2) using the CSS "Sprite chart"

is to merge the scattered images into a larger image, using CSS for background positioning. The benefit is to reduce the number of requests and improve the overall loading speed of the picture.

But it also has some drawbacks:

For example, a large number of pictures merged into a larger image, need to calculate accurately, carefully adjust the position, simple hand-made is a very complex thing. (Fortunately, there are some tools available for us to do.)

In addition, the maintenance process is complex, to try to make the existing picture to keep the original position unchanged, if the size of the background map caused the original area can not be placed, then have to give up, if not to change in the original position, then the remaining picture style needs to be modified, is very cumbersome process. The newly added picture is best placed on the last side.

There is also the use of improper can cause performance problems, the biggest problem is memory consumption. If the production process does not do any planning, randomly placed, it may make the picture becomes quite large, thus occupies the memory.

Here are some best practices:

1. Applying CSS Sprite technology in the late project

Because generally in the development process, will be more frequent changes or change pictures, if this time using sprite technology, will add a lot of development costs.

2, reasonable organization "sprite" figure

If you want to put all the pictures on a picture, there will be inappropriate, maintenance is not very convenient. The organization background chart is divided mainly by the style of the module and background map. For example, as thumbnails of the show together, comments, likes, up and down arrows and other icons put together and so on.

3, control "sprite" Figure size and size

Because the large size of the picture will occupy a lot of memory, so to control in a reasonable size, the recommended length and width multiplication not more than 2500, size within 200kb

4. Reasonable control of the distance between the background map units and the location of the background map

This principle is designed to prevent the area from appearing in other unrelated background plots when the background map is smaller than the element size.

5. Using related tools to process the sprite

Third, reduce the amount of CSS code

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

(1) Define concise CSS rules

Merge related rules, define concise property values

Merge rules are like font-family, Font-size, Font-weight, and so on, which can be merged into a font. Concise attribute values, such as color values: colors, #33AAFF可以简化为 #3af, and so on.

(2) Merging the same definitions

There are always some modules in the Web page with a higher similarity, you can share the same part of the definition, the different parts are defined separately. And in CSS, many properties can be inherited, only need to be defined in the appropriate place once.

(3) Delete invalid definitions

Invalid definition, does not affect the page function display, but will affect the performance of the page display, increase the amount of code, but also increase the time of the browser parsing code. Invalid definitions include invalid rules and invalid style attributes, which are generally introduced during development, and cannot be intuitively judged, and can be found in CSS with tools that are not available in chrome.

Other CSS high performance practices

(1) Avoid using @import

@import imported new style files prevent parallel downloads of the page, which increases the overall load time of the file.

(2) Avoid using the Internet Explorer unique style: Picture filters and CSS expressions

The use of image filters blocks the loading and rendering of the browser when the picture is loaded, and adds additional memory overhead. The role of CSS expressions is to dynamically set CSS properties, the expression is not only a compatibility problem, as well as performance problems, such as browser size changes, window changes, will make the browser frequently calculate, performance is very expensive. The same effect can be achieved with JavaScript.

CSS3 Best Practices

View browser support

One of the most frequently asked questions during our use of CSS3 is: how compatible? No way, with the development of CSS, it can provide us with a lot of problems before the problem of a better solution, so we can't help but think can do that. PC end has been criticized the IE series, to the mobile side will be much better, but some still not very good. Therefore, viewing browser support is almost an essential action. If the use of features is only decorative embellishment effect, do not affect the overall situation, there is no need to consider too many compatibility issues, if the design requirements, must support all browsers, you have to pay special attention. Developers can choose from such as: caniuse.com, CSS3 Click Chart, CSS contents and browser compatibility these online tools to see compatibility.

Add the necessary browser prefixes

For friends who just use CSS soon, if occasionally in the source of a site to see such as: "-webkit-、-moz-", etc., may feel very strange, what is this? They are prefixes that correspond to different browser vendors.

Because browsers may only implement a previous version of the standard definition when they support CSS3, standard notation is not yet supported, and adding a browser prefix to the code can be frustrating, making the code more difficult to maintain.

But it's not for "perfect". Compatible with all browsers, generally according to the browser or system version of the market share and target users to use the proportion of the browser, to decide to add the prefix and add several prefixes. And believe that with the gradual development, the system, the browser is constantly upgrading, updating, the need to use the prefix will be reduced.

The problem comes again, since the need to add the necessary prefixes, stating that sometimes it is necessary, it has to add the case, it is not very troublesome? The same rule should be written three or four times, may be used in many places, how is good? Don't worry, here are a few countermeasures:

1. Use tools to add browser prefixes for CSS properties

PREFIXR, the code can be processed at a later stage of development. It will automatically add the required prefixes and delete unnecessary prefixes.

Autoprefixer, if you want to be more autonomous in the development process, you can use this tool, developers can customize the scope of browser support, it also has a variety of uses, can be integrated into multiple development environments. There are also several tools to use: Cssfx, *css agent* and-prefix-free.

2, with the help of CSS preprocessing technology

At present, there is sass, less, the specific method is to define a template style for the CSS3 style attributes. The advantage: Avoid a lot of duplication of code, only need to maintain a definition.

3. Do not over-add browser prefixes

Some developers in order to be compatible with all browsers, regardless of the circumstances of the CSS code to add all the browser prefix, this is a negative encoding, adding too much duplication of code, reduce the parsing performance of the browser, increase the complexity, and some of the attributes of the prefix may not be supported by the browser.

4. Add CSS3 Standard attribute definition

What is a standard attribute definition? Just because you don't need any browser prefixes, you might notice that many of the places where you use CSS3 write standard attribute definitions in the final place, why? Because when the browser supports the standard properties, it can overwrite the previously added prefix definition, the attribute standard definition in CSS3 is the definition of conforming to the specification, adding the definition of the browser prefix will be phased out as the browser updates.

Of course, it is also important to note that some of the properties are currently owned by only WebKit or only Firefox, then there is no need to write the standard definition and other browser prefixes.

Doing a good job of compatibility processing of new features in CSS3

When it comes to compatibility, it mentions low-version ie, such as very common fillets, transparent images, and so on, sometimes we degrade them, such as filter or JavaScript, use box-sizing, transform, recommend using Modernizr, This framework contains a number of compatibility scenarios for CSS3 new features.

No matter what kind of program, will bring the performance of the loss, can not be indiscriminate abuse, still need everyone to weigh and choose. Recommend a more efficient way to use the HTML5 website: html5please. The Web site uses a way to divide the new features in CSS3 into three categories:

(1) Direct use

Contains most of the new features, some features themselves do not affect compatibility, such as Border-radius, media queries, etc., some need to add degraded processing, such as multi-background map, to set a single background or background color as an alternative.

(2) Use with caution

This is primarily a performance issue, such as when a box shadow is applied to an element that occupies a large area, and when the page scrolls or hovers over the mouse, it can cause minor performance problems.

(3) Avoid using

This is partly because they may only support a browser, such as a reflection, and you need to avoid it.

To sum up, CSS can be used to lift high-performance methods or quite a lot of, but we are easy to ignore them, because they bring the impact seems not so obvious, and, many people may be convenient for the diagram, arbitrary sway of their own talent, how to write on how to write, can achieve the effect on the line, which is a little negative ha, Forget about your good engineer goals, MA ' am?! ~~CSS rules, though not easy, is not easy to write, or to some of the pursuit of the ultimate spirit drops. Gentlemen and write and cherish it! ~

High-Maintenance CSS

What are some of the features of CSS?

In simple terms, use: inline, inline, external, import. How to style elements: element tag names, class names, IDs, various selectors, and their combinations. So, it is very flexible, if you do not do any of the specifications of the restrictions, it will certainly lead to the confusion of CSS code and difficult to maintain.

How to organize CSS code efficiently?

The structure is clear, the module is distinct, the reasonable code organization structure can improve the reusability and maintainability of code, and reduce the development complexity. How do you organize it?

The first is the organization of code files, can be divided into two categories: General class and business class. Then, there is a file to reset, the common name is reset or default, normalize and so on.

There is a file for the general module and some basic style, often named mod, common, etc., such as the page dialog box, cue box, head, bottom, sidebar, etc., will be used in multiple pages, such aspects of the page reference, improve code reuse degree.

Another need for a file to be compatible with the old version of IE browser style, the benefits of doing so have two:

One, reduce the burden of non-IE browser loading style files

Second, if the future decision no longer support the old version of IE browser, then only need to modify a file, do not need to find multiple files everywhere to modify. Of course, in dealing with browser compatibility, there is a principle of whether there are other solutions that do not have compatibility problems, and if not, put the part that is compatible to a separate file.

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

This can cause a problem, a page is not to introduce a lot of files? is the HTTP request not much more when the page is loaded? In fact, it is not contradictory, the file is divided only for the convenience of development and maintenance, when the release will use the tool to consolidate multiple files into a file, so do not worry about the introduction of multiple files problem.

It is said that the organization of the file, then in the file also in accordance with certain rules to organize the declaration of the style. For example, according to the level of elements in the module, if it is a sibling, according to the element in the page position, from top to bottom, or from left to right, if there are more than one element share the same declaration, you should first declare the common style. If this is not enough, you can use some more advanced methods, such as less, sass, which give CSS the properties of dynamic languages such as variables, inheritance, operations, functions, and so on.

The above is said from a few big directions, the following involves a few points to talk about

Using the CSS Reset Unified browser Display effect

First of all, the HTML tag is original style, but the problem is in different browsers, the default style of the label is not the same, some of the differences to the development caused trouble, as early as in 2004, someone developed the first reset style file, called undohtml. Css, followed by a variety of reset scenarios, in which there is a scheme "hot for a while", this scenario is 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 the subsequent development, and not very effective to improve the overall development efficiency. In addition, the performance of this scenario is poor, which affects the performance of page rendering when there are many page elements. So, people are still gradually exploring a better way to reset, there are currently several popular reset schemes that have Eric Meyer developed by the reset CSS and Yahoo's front-end technical team developed by Yui Reset CSS. In fact, there is no one solution for all projects, so it is better to choose to refer to other people's plans and then design a plan that suits your project.

Here are a few points to consider:

(1) HTML5 new tags need to reset their display style because they are not defined by default display styles in low-version ie.

(2) Padding, margin, border tags in the browser differences are mainly related to these three styles of the default style generated, but also do not need to reset all the elements of the margin, padding, border, should be based on the actual situation.

(3) Font settings

(4) Other elements of the style reset typically have the LI default list item style, the default space between table cells, an underscore for a link, and so on.

Sort CSS Definitions

CSS is not strong logic, arbitrary writing does not affect its role, if the use of tools to sort it will be very cumbersome, so few people will care, but the sort is still good.

Like what:

1, more tidy

2. Prevent duplicate definitions

3, can clearly view the definition

4, follow-up maintenance can quickly locate

Sort by:

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

2, alphabetical alphabetical order, the advantage is simple rules

3, by definition length according to style defined character length arrangement

Each has the merits and demerits, the actual application, the recommendation uses the first kind. But it is also difficult to do so in the writing process by the front-end engineers, which can be written in the most efficient way, using tools to sort the CSS when committing the code. It improves efficiency and facilitates subsequent code reading and maintenance. There is a free tool that is csscomb.

Reasonable use of CSS weights to improve code reusability

What is the weight, that is, the precedence of CSS's many types of selectors, and the high-priority style overrides the low-priority style. Weight of more specific rules, you can access the information, here do not repeat.

Here's how to define the appropriate selector according to the weight of the selector:

(1) Try not to use the ID selector

A page is not allowed to define two identical IDs, and the ID selector weights are high, if you want to overwrite the element style using the ID selector, you must add a new selector on its element, or use! Important, such a result would make it more difficult to reuse the style code. The best practice is to use a lower-weighted selector as the base style whenever possible.

(2) Reducing the hierarchy of sub-selectors

is also the process of reducing the overall weight of the sub-selectors, and the less the hierarchy, the lower the dependency on the HTML structure. Another reason for the excessive level of CSS is the misuse of tools such as sass and less, which I am aware of at the beginning of my use, because you can define styles using nested and referenced methods, so that you save yourself a lot of effort, but the files are eventually compiled. We don't have to hit that much code over and over again, but the generated code will still be a lot, so it's convenient for you to pay special attention to reducing the selector level.

(3) using a combined CSS class selector

In this way, developers can avoid the problem of CSS style coverage, avoiding the process of calculating the weight of the selector, while improving the reusability of the Code, the concept of composition is a complex parent class in the variable part and the stable part of the division, the stable part as the main class, the variable part into a few simple classes, There is no inheritance between classes and classes, which can also play a role in reducing dependency on HTML structures and improving code reusability.

How to be compatible with IE browser?

IE8 and the following version of IE browser has been the front-end developers heart pain. In order to be compatible with them and make extra code to become hack code, people often don't want to write that code. Here are some practical ways to be compatible with IE browsers.

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

One is a bug in the browser itself, one of which is incompatible with the standard or does not support the standard.

(2) Separation style compatible code

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

EM, px or%?

The reason to talk about this topic is that the page function is becoming more and more, more and more devices are used to access the page, the layout of the page is a challenging thing, and the size and font of the elements in the page and the size of the pictures are closely related to the layout. In view of this, front-end development began to focus on how to improve the page layout, the core idea is to set the page element size and font size to a relative value. Font-relative units include: Em, EX, CH, rem. More details are not required, there is more information to explain. Here are a few best practices:

(1) Try to set the relative size

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

(2) Absolute dimensions are used only in the case of a predictable element size

For example, the design requires the use of absolute width, such as the overall width, the width of the sidebar, the height of the end of the page fixed, etc., in the display of pictures, video, the appropriate fixed size will allow these multimedia elements to show the best results.

(3) Use EM to set the font size

Using PX to set the size of the font is not good, the use of percentages to set the font size is not customary, the best way is to use EM to set the font size, but with the increase in the level of font settings, this way instead of increasing the cost of maintenance, for this, CSS3 introduced REM units, is relative to the root element of the font size calculation, avoids this problem, currently in addition to IE8 and below, most browsers support it.

This article a lot of things are donuts, hope to some novice have certain guide role, bring certain help. Each person in their own gradual practice will have some such feelings and experience, lessons, often summed up and put into their next practice, I believe it will be very good. Let's cheer together! ~

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.