Talking about CSS design patterns

高洛峰
Release: 2017-02-09 17:05:58
Original
1189 people have browsed it

What is a design pattern?

Someone once ridiculed that design patterns are used by engineers to show off to others and make them appear superior. Someone once said that it is not that design patterns are useless, but that you are not old enough to understand them and can use them. when.

First, let’s take a look at the more official explanation: “Design pattern is a set of classified code design experiences that are used repeatedly, known to most people, and summarized. The purpose of using design patterns is to be able to Reusing code makes it easier for others to understand and ensures code reliability. There is no doubt that design patterns are win-win for ourselves, others and the system; design patterns make code preparation truly engineering; design patterns are the cornerstone of software engineering. Context is like the structure of a building. Today we will talk about CSS design patterns.

Design pattern, this term is common to us. Almost all programming languages ​​have several sets, but not many people study it in depth. The reasons are as follows:

1. There seems to be no need to Emphasize it, if there are any problems, just change it or follow the team norms;

2. It doesn’t hurt not to use some existing models;

3. The amount of business that many people are exposed to The level has not yet reached the level that requires planning and organization. Just writing the layout, writing special effects, and taking care of compatibility are enough to drink a pot, and there is no consciousness to think about some methodological issues.

Of course, I have experienced all three of these, and I believe you have too~

We will all grow up, and we will slowly do more, larger, and more complex projects. This At this time, we need to think about some issues from top to bottom and throughout the entire process. I won’t talk about the backend, but only the front-end, such as: style formulation, color tone, modules, layout methods, interaction methods, logic, etc. If you add teamwork and there is no plan, it won’t be long before those things that look like nothing Problematic code will expose various problems, such as module naming, class naming, file organization, extraction of shared modules, code reuse, readability, scalability, and maintainability. They seem to be just simple little actions, but they require you to look further to avoid future problems that require paying a greater price, or even being forced to restructure the entire project. It can be said that the merits are in the present and the benefits will be in the future~

Since CSS is to be designed, it must have some problems or flaws. Among them, one of the most obvious is that any of its rules is a global statement that will affect all related pages in which it is introduced. Elements work, whether that's what you want or not. Independent and composable modules are the key to a maintainable system. Next, we will discuss from multiple levels how to write CSS in a more scientific way.

Starting from needs

Points

When we first start learning to write, we don’t think about whether a certain sentence is good or not, and whether the structure of the article is appropriate. , because we are not aware of it. The same goes for writing code. At the beginning, we just define the rules. If we can use the right attributes and correct syntax, then we can implement the page. Slowly, you will find that the page also has a structure. Would it be better if we organize the code according to the structure of the page? For example, it is divided into header, navigation, sidebar, banner area, main content area, bottom, etc.

However, this seems to be not enough, because there are still some things that are highly reusable and cannot be classified as any inherent module, such as breadcrumbs, paging, pop-up windows, etc., they If it is not suitable to be placed in the code of a certain inherent module, you can separate a piece of exclusive css and js separately. Perhaps, this is the origin of componentization~

 Dismantling

After that, our code looks much better than before, with clear organization and greatly improved maintainability. However, it seems that it is still not enough. We will find other things that are very small but have a high degree of reusability. They are also not Suitable to be placed in modules, such as borders, backgrounds, icons, fonts, margins, layout methods, etc. If we define them once in every place where they are needed, they will be repeated many times. Obviously, this deviates from good practice and will cause code redundancy and maintenance difficulties. Therefore, we need to "dismantle" it. What will happen after it is dismantled? We can add it directly wherever we want to use it, and change it uniformly when we need to change it.

Arrangement

After "dividing" and "dismantling", our code structure has been very clear. Each content module, function module, and UI module are all waiting to be called. So what is left? ? Yes, orderly organization is still needed. After the classification is clear, it still needs to be arranged in an orderly manner. If we consider it from different dimensions, we can always strive for excellence. For example, we may see something like this:

@import "mod_reset.css";
@import "ico_sprite.css";
@import "mod_btns.css";
@import "header.css";
@import "mod_tab.css";
@import "footer.css";
Copy after login

We place the different parts in a certain order so that our code can be seen It looks more organized and easy to maintain. At the same time, it is conducive to inheritance or cascading coverage. Don't underestimate this step. It may seem dispensable, but it actually requires relatively high overall planning capabilities, which can reduce redundant code and quickly locate problem locations.

In addition, we can still have other methods to help us distinguish the code range, such as:

 1. Create a brief directory at the head of the file

谈CSS的设计模式

 2. Use block comments

谈CSS的设计模式

In the comments, you should try to write the purpose of the code, state switching, adjustment reasons, interaction logic, etc. in as much detail as possible. This will not only facilitate your own maintenance, but also help others take over and maintain your code.

Starting from the conclusion

In addition to some common parts of the requirements, there are other things that need attention but will not be formally defined. They come from our practical experience, such as:

Don’t nest the levels too deeply

Anyone who knows a little bit about browser rendering principles knows that when parsing CSS rules, it traverses from right to left, layer by layer. If the layer Too much will inevitably increase the rendering time and affect the rendering speed. In addition, if there are too many levels of selectors, it will indirectly reflect that your HTML structure may not be concise enough.

So how many layers are appropriate? The general recommendation is not to exceed 4 floors, but then again, what will happen if it exceeds 4 floors? There won’t be much obvious impact, unless you write a terrifying amount, or the project is extremely complex, you may be able to see the impact. In fact, from our daily needs, within 4 layers are enough to solve most problems, so it is reasonable.

Avoid using element selectors

For two reasons:

The first point is related to what was mentioned in the previous paragraph. In HTML, there are many commonly used high-level elements. Frequency elements, such as p, p, span, a, ul, etc. If you use an element selector in the innermost layer of a multi-level selector, then when starting to search, the browser will traverse all the elements in the HTML. Obviously, this is not necessary.

The second point is that there are potential changes in our needs and code structure. If we write a page today, we may need to add a button, a sentence, and more tomorrow. an icon. A structure we have written may be reused in other structures at any time. Therefore, if you use an element selector to determine something, whether it is a newly added thing or a reused thing added to other structures, it is very likely to cause style conflicts. At this time , you have to write redundant styles to overwrite and correct, or redefine the class.

Therefore, for the above considerations, try not to use element selectors in specific code modules. The premise of using element selectors is that you are completely sure that it will not cause problems. Note that the scope I used is "specific code module", so the style used to define general rules is acceptable and recommended, such as reset. It can also be elsewhere, which requires our own consideration.

Avoid using group selectors

What are the problems with group selectors? Just go to the picture.

谈CSS的设计模式

This situation in the picture is rare. Here is just an example. Three sets of selectors are written here to define the same style in different places. The obvious flaw is that if there is a fourth place that needs to be used, you have to add another set of selectors. If there are 10 different places, do you write 10? This is very painful for maintenance. How can we, smart people, be troubled by such complicated and unnecessary labor. Therefore, Wall Crack does not recommend this approach. You can completely extract a public class and define a unified style. Then, wherever you need to place it, reuse and maintenance will be more convenient.

Of course, you may say that when I wrote the first one, I didn’t know that there would be so many more. I don’t know whether it is necessary to extract it. Yes, so you need to do it based on experience. Judgment also requires timely organization and reconstruction of the code during the project advancement process.

The number and order of file introductions

For friends who are new to web pages, these two points are easy to ignore, because they don’t seem to have much impact. How many times do you request it, and whether the style is Already loaded, it’s not that easy to drive people crazy. However, due to the ultimate pursuit of user experience, we still hope that the number of file requests should be as small as possible, the content should be displayed in a priority order, and the files should be loaded in an order. In this way, when it is really difficult to reduce the file size, users can see more important and normally displayed content first.

The above are just a few examples. For more practical conclusions, you can read more relevant blog posts or books, and you will find the experiences of seniors.

Starting from Contradiction

Universality and Semantics

Naming convention is beneficial for immediately understanding which category a particular style belongs to and its role within the overall scope of the page. On large projects, it is more likely to have styles broken up across multiple files. In these cases, naming convention also makes it easier to find which file a style belongs to. . In large projects it's more likely to have styles that are broken across multiple files. In this case, the naming convention can also make it easier to find which file a style belongs to.

Many times, we need something to be defined as universal for reuse, such as module title, button, prompt text, icon, etc. At the beginning, we are used to looking at the content of the visual draft. If it is "news", we will define "news", if it is "about", we will define "about", if it is a red button, we will define "red-btn", etc. This will cause a problem. If there is another one following The news list has similar style and structure, but it is not news. What should I do? It is obviously inappropriate to continue to use "news", which tells us that we cannot limit our attention to content and need to separate content and structure.

We can’t use “news” anymore, so what should we use? abc? 123? In this way, there will be no conflicts, and everything will be fine~ In fact, this is another extreme. Although it avoids conflicts with other modules to a large extent, its own readability is greatly reduced. Others, Even you yourself will forget what it is after a while, which is very detrimental to teamwork. As for what kind of naming method needs to be used, you need to plan it based on the overall project. What characteristics are suitable for distinguishing different structures, and it can also make it easier for people to establish a connection between the name and the structure, such as the category it belongs to. , functions, pages, etc.

Team and Individual

In a team, everyone has different experiences, coding levels and habits. This will cause each person to write in his own way. You use underscores and I use underlines. ;I use the full spelling in English, you use the abbreviation, etc. Although there is nothing right or wrong about these, they cause considerable obstacles to collaboration among team members. Others must spend time adapting to and understanding how you organize and define, which invisibly increases the cost.

Therefore, there is a need for the existence of "team specifications". In addition to some writing regulations, the specifications make our code more unified, clear, more readable, and more recognizable. You can also extract some best practices and reused modules, which is beneficial to everyone in the team.

Of course, for people, the most difficult thing is to adjust existing habits. This will cause the pain of "transformation" after entering a team. In fact, this pain is also the pain of growing up. You will Learn better coding methods and better practice methods, and consider the value and significance of something from the perspective of the project or team as a whole.

CSS and Preprocessor

I have previously talked about CSS preprocessor in detail in an article. I used to reject it because of the cost of learning and because I felt it was unnecessary to apply it. But once you decide to learn to use it, you will feel that it is not like that. When the preprocessor introduces itself to you, it specifically emphasizes that its syntax is fully compatible with CSS. In other words, when you use LESS Or in a SASS file, there is no problem in writing CSS code directly. In addition, it can provide us with many conveniences, such as defining unified variables; using nesting instead of repeatedly writing selectors; being able to extract common code blocks and reuse them easily, etc.

Therefore, when we have organized and written CSS well, the preprocessor will give us a pair of wings again, allowing us to code more flexibly and efficiently.

Starting from the existing models

Let’s briefly look at some widely circulated models. (ps: The order has nothing to do with ranking, quality)

1. OOCSS - Object Oriented CSS

Anyone who has been in contact with computers should know that OOP - Object Oriented Programming, if you are When you first come into contact with OOCSS, you will be confused. Is it "object-oriented CSS"? It is not a real programming language. How is it object-oriented?

OOCSS was first mentioned in 2009. Its two major principles are:

Separating structure from skin and container from content.

The literal translation is, The structure and skin are separated, and the container and content are separated.

That is to say, the structure, skin and content should not be strongly coupled, but should be independent of each other. The goal to be achieved is to make it easier to reuse and combine, and you can choose to use it, choose to quote it, etc.

 2. SMACSS——Scalable and Modular Architecture for CSS

Practically speaking, OOCSS gives an idea worth learning from, but in terms of code organization, it does not provide Come up with specific implementation methods. From this point of view, SMACSS goes one step further.

Its core is:

1. Base

Basic styles are general fixed styles that need to be defined first and are targeted at a certain type of elements.

2. Layout

Layout style is related to the overall structure of the page, such as lists, main content, sidebar position, width and height, layout method, etc.

 3. Module (module)

Module style is the module that we extracted and classified during the process of dismantling the page. These styles are written together separately.

 4. State

Certain elements in the page will need to respond to different states, such as available, unavailable, used, expired, warning, etc. These styles can be organized together.

5. Theme

Theme refers to the color, style, etc. of the entire layout. Generally, websites do not have frequent major changes. The one that impressed us the most is QQ There are not many other applications of space, so this is generally not used, but it is good to have such an awareness. When you need to use it, you will know how to plan.

With the above 5-point classification strategy, when our code is organized, the ideas will be very clear and the arrangements will be very orderly. Another advantage is that it can solve the difficulty and confusion of naming. The reason for this problem , the main reason is that we don’t know what standards to use to define the belonging and characteristics of elements. After we have classification, we will not name them casually and confusingly. With the basis, it will be easier and less likely to conflict.

3. Meta CSS

Atomic classes can also be called "semantic" classes, like this:

谈CSS的设计模式

Its What are the characteristics? Style has nothing to do with structure or content. You can pre-define such a set of rules and add them where needed. I believe that when everyone sees this writing method for the first time, they will think: Can it still be written like this? ! Yes, there are always some people, some new ideas and methods will emerge, and it is one of them. Of course, it is not praising how good it is in itself, but saying that this phenomenon and process is good in itself. People often complain about it, such as: "Is there any difference between writing like this and directly inlining it?", "If you want to adjust the style, you have to change the HTML, which makes maintenance more troublesome and goes against the original intention of separating style and structure" etc. In fact, I Personally, I don’t agree with the above writing method. If you want to extract these, what else can’t be extracted? Moreover, these attributes are not very common between projects, pages, and modules. Extracting these is just a little lazy and saves effort, but in order to take care of more situations, you must Writing redundant code is not worth the gain.

Although it has shortcomings, I personally support the separation of other things, such as: float (float), text layout (text-align), Flexbox layout, etc. These are values ​​​​that do not have so many possibilities. Moreover, it is frequently used, easy to reuse, and has few changes. In addition, you can also extract some other public small granular categories, such as types of buttons, types of text colors, etc. These have nothing to do with CSS itself, but are related to the project. This is to borrow its ideas rather than directly use them.

4. BEM

Strictly speaking, BEM is not a set of flesh-and-blood patterns, nor is it limited to planning at the CSS level. It is a way to organize, The idea of ​​writing code, and it seems simple, has a huge impact on the front-end world.

Its core is as follows:

Block, Element, Modifier

It helps us define the level attributes of each part of the page, In a sense, it is also a kind of "demolition". The naming rules are as follows:

谈CSS的设计模式

Its appearance has inspired many people, but some people still have a picky attitude, such as:

 1. The style is not uniform, and the code seems not clean and beautiful enough

 2. It may cause the class name to be too long

As mentioned before, you don’t need to use it directly, but you must be clear Its advantage: it allows us to know which code belongs to a module and its role in the module just through the class name. Then learn from it.

Of course, BEM has gathered the efforts of many people and has received a lot of praise, including the authors of OOCSS. So, it's definitely not that simple. It will also tell you how to write with js, how to organize your files better, how to build the project, etc. Details can be found on the official website.

Based on reality, you are the one who decides the result

How to use design patterns?

Although there are mature design patterns, in practice, you may feel that none of them are completely consistent with your project, or you have to make adjustments to use them, which is very costly. In fact, we don’t need to cater to patterns. To make patterns work for us, you need to understand the principles behind them, know how they solve what problems, and then learn from them and use their methods to solve our problems. Okay, so there is no need to worry about whether to use it or not, and there is no need to worry about which one to choose. It is not simply about which one is good and which one is not good. There is always a place where we can use it. The sea embraces all rivers and brings together the strengths of hundreds of schools of thought.

Another point of view that I personally have always insisted on is that the troika of front-end development - html, css, js, do not and cannot talk about how good or how good they are in isolation. We rarely do. There are codes or modules that are only used once, and there is no one language. The troika all collaborate together, and there are multiple factors in it such as reuse, expansion, and teamwork. Therefore, we cannot have the idea that: I am doing this now, it is the only one, it is fixed, and there is no problem. In fact, many problems are potential and should be viewed with a development perspective. Between project files, between projects, between team members, no matter where your division of labor is, you must consider the impact before and after and the inconvenience that may bring to cooperation.

 What is the best practice? Only with "practice" can there be "best". Talking about the best without the actual situation is just a castle in the air. So, the best model is not a classic model, but one that is constantly adjusted during the project. Therefore, you no longer need to be afraid of design patterns that seem unclear, and you don’t need to be depressed because you don’t understand design patterns. It is a practical method summarized by people, and you can also have your own pattern~

For more about CSS design patterns, please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template