What are design patterns?
It has been joked that design mode is used by engineers to show off with others, appear lofty; It’s not that design patterns don’t work, it’s that you’re not old enough to understand them and use them.
Let’s start with the official explanation: “A Design pattern is a set of repeated, well-known, classified code Design experiences. Design patterns are used to re-use code, make it easier for others to understand, and ensure code reliability. There is no doubt that design patterns are win-win for themselves, others, and systems; Design patterns make coding truly engineering; Design patterns are the cornerstone of software engineering, just like the structure of a building.”
Today we are going to talk about CSS design patterns.
Design patterns are a common term. Almost all programming languages have several of them, but few have studied them in depth for the following reasons:
1. There seems to be no great need to emphasize it. If there is a problem, change it or follow the team’s norms. 2. It doesn’t hurt to not use existing patterns; 3, many people have not yet reached the level of business planning and organization, just write layout, write special effects, care compatibility, enough to drink a pot, there is no consciousness to think about some methodological problems.
Of course, these three are my experience, I believe you are ~
We all grow up and gradually do more, larger and more complex projects. At this time, we need to think about some problems from top to bottom and in the whole process. We only talk about the front end instead of the background, for example: Constituting the style, color, module, layout, interaction, logic and so on, if coupled with the team, if there is no a plan, before long, the code looks fine, will be exposed various problems, module name, class name, file organization, sharing the extraction of module, code reuse, readability, extensibility and maintainability. They look like simple small actions, but you need to look further, to avoid problems in the future will have to pay more cost, or even forced to restructure the whole project, it can be said that the success in the present, the benefit of the future ~
There are certainly some problems or flaws with CSS design, one of the most obvious being that any rule is a global declaration that applies to all relevant elements on the page it is introduced into, whether you want it to or not. Independent and composable modules are the key to a maintainable system. Let’s take a look at how to write CSS in a more scientific way, from multiple levels.
Start from need
When we first learn to write, we don’t think about whether a sentence is good or whether the structure of the article is appropriate, because we are not aware of it. The same goes for writing code. At first, we just define rules, use the right properties, syntax, and implement the page. As time goes on, pages have structure, too. Wouldn’t it be better if we organized the code according to the structure of the page? For example, split into headers, navigation, sidebars, banner area, main content area, bottom, and so on.
However this is not enough, because there are a few things, reuse degree is high, the bad and put it into any inherent modules, such as: bread crumbs, paging, pop-up window, etc., they are not suited to be put into a certain inherent module of code, you can separate out a exclusive CSS and js, perhaps, this is the origin of componentization ~
After dismantling the points, our code looks already much better than before, the organization is clear, improve the maintainability, but, as if not enough, we will find something else, is very small, but reuse degree is high, they don’t fit in same module, for example, borders, background, ICONS, fonts, margins, layout and so on. If we define them once for every place we need them, they will be repeated many times, which obviously deviates from good practice and leads to code redundancy and maintenance difficulties. So, we need to tear it down. What happens after you dismantle it? Where we want to use it, we can add it directly, and we can change it when we need to.
After the platoon “divided”, “disassembly”, our code structure has been very clear, each content module, function module, UI module are clever waiting for the call, so what is the difference? Yes, there is still a lack of orderly organization. After the classification is clear, there is still a need for orderly arrangement. We can always keep improving by considering different latitudes. For example, we might 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”;
We put the different parts in order to make our code look more organized, easier to maintain, and easier to inherit or overlay. Do not underestimate this step, which seems to be dispensable, but actually requires relatively high overall planning ability, which can reduce redundant code and quickly locate problems.
In addition, there are other ways to help distinguish code scope, such as:
1. Create a brief directory at the top of the file
2. Use block annotations
In the comments, should be as detailed as possible to write clearly the purpose of the code, state switch, adjustment reasons, interaction logic and so on, so that not only conducive to their own maintenance, more conducive to others to take over the maintenance of your code.
Proceed from conclusion
In addition to some general parts of the requirements, there are some other things that need to be noted, but will not be formally defined, which are derived from our practical experience, such as:
Do not nest the hierarchy too deeply
A little understanding of some browser rendering principles know that it is in the resolution of CSS rules, from right to left, layer by layer to traverse to find, if too many layers, will inevitably increase the rendering time, affect the rendering speed. On the other hand, if you have too many selector levels, your HTML structure may not be concise enough.
So how many layers is appropriate? The general advice is no more than 4 floors, but then again, what happens if you go beyond that? It’s not going to have a significant impact, unless you write about scary numbers, or projects that are extremely complex, you can see the impact. In fact, from our daily needs, 4 floors is enough to solve most problems, so it’s reasonable.
Avoid element selectors
For two reasons:
Mentioned on the first point, and a related, in HTML, there are many commonly used high frequency elements, for example, div, p, span, a, ul, etc., if you used in multilayer selector of the innermost element selector, so, when to start looking for browser will iterate through all the elements in the HTML, obviously, it is not necessary.
Second, our requirements and code structure are potentially changing. One day a page is written, and the next day a button, a sentence, and an icon may be added. We write a good structure and could be reused by other structures at any time to go, so, if you use the element selector to set something, whether it is a new added, or by reuse things added to the other structure, style will most likely come in conflict, at this time, you have to write extra cover fixed style, Or redefine the class.
So, for the above reasons, try not to use element selectors in specific code modules, if you are absolutely sure that it will not cause problems. Note that I limited the scope to “specific code modules,” so the styles used to define general rules, such as reset, are acceptable and recommended. It could be somewhere else, and that’s for us to figure out.
Avoid group selectors
What’s wrong with the group selector? Go straight to the picture.
You don’t see this very often, but here’s just an example, where you have three sets of selectors defining the same style in different places, and the obvious drawback is that if there’s a fourth place to use, you have to add another set of selectors, and if there’s 10 different places, you put 10, right? This is very painful for maintenance, smart we, how can be so complicated and unnecessary labor trouble, therefore, the wall crack does not recommend this practice, can be extracted from a common class, define a unified style, and then, where need to put where, reuse and maintenance will be more convenient.
Of course, you might say, when I wrote the first one, I didn’t know there were so many more, and I didn’t know whether it was necessary to extract, yes, so you need to judge from experience, and also need to organize and refactor the code as the project progresses.
The number and order in which files are introduced
For new to web friends, these two points are easy to overlook, because they look it’s not a big impact, more than a few times request, whether the style is already loaded, crazy people are not so easy, but the ultimate pursuit for the user experience, we still hope to file request times, less as far as possible the content shows a priority, a sequence file is loaded, This allows the user to see the more important, normally displayed content first, when it is really difficult to reduce the file size.
The above are just a few examples, more practical conclusions, you can read more relevant blog posts or books, there will be predecessors’ experience.
Start from contradiction
General and semantic
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.
Naming rules help you immediately understand which category a particular style belongs to and what it does in the overall scope of the page. In large projects, it is more likely to have broken styles in multiple files. In this case, the naming convention also makes it easier to find out which file a style belongs to.
Many times, we need something to be defined as generic for reuse, such as: Module title, button, prompt text, icon, etc. At the beginning, we used to look at the content of visual draft. If it was “news”, we would define “new”, if it was “about”, we would define “red-bTN”, etc. This would lead to a problem. What if there is another news list with a similar style and structure, but not news? Continuing to use “new” is clearly inappropriate, which tells us that we need to look beyond content and separate content from structure.
I can’t use “new”, so what do I use? ABC? 123? In fact, this goes to the other extreme. While it largely avoids collisions with other modules, the readability of the module itself is greatly reduced, and others (and even you yourself) will forget what it is after a while, which is very bad for teamwork. As for the need to use what kind of naming, you need to plan according to the overall project, suitable for distinguishing different structures according to what characteristics, and can make it easier to establish a connection between the name and structure, such as category, function, page and so on.
Teams and individuals
In a team, people’s experience is different, coding level and habits are also different, so that one person will write a way, you use the underline, I use the underline; I’ll do it in English, you do it in shorthand, etc. While there is no right or wrong way to do this, it creates a significant barrier to collaboration between team members, and it takes time for others to adapt and read how you organize and define, which increases costs intangibles.
Therefore, there is a need for the existence of “team specifications”, specifications in addition to some provisions on writing, so that our code is more unified, clear, more readable, more recognizable. You can also extract best practices, reuse modules, and so on, to the benefit of everyone on the team.
, of course, for the people, the most difficult to adjust the existing habit, it will have to enter a team after the “transformation” pain, actually this kind of pain is growing pain, you will learn better coding methods, better practice, from the project or team as a whole to consider the value of one thing and meaning.
CSS and preprocessors
I have in front of the article in detail about CSS preprocessor, I once it is exclusive, because learning cost, because the application up and there is no need to feel, but once you decide to learn to use it, will find it’s not that, when the preprocessor to introduce you to it’s own, there is emphasized, its syntax and CSS is fully compatible, that is to say, There is no problem writing CSS code directly in LESS or SASS files. In addition, it can provide us with a lot of convenience, such as defining uniform variables; Use nesting instead of writing selectors over and over again; You can extract common blocks of code and reuse them easily and so on.
So, once we’ve got CSS organized and written well, the preprocessor again gives us wings to code more flexibly and efficiently.
Start with existing models
Let’s take a quick look at some popular models. (PS: Order has nothing to do with ranking or quality)
OOP — Object Oriented Programming, if you are the first time to contact OOCSS, you will be very confused, is it “Object Oriented CSS”? It’s not really a programming language. How object oriented?
OOCSS, which was first mentioned in 2009, has two principles:
separating structure from skin and container from content.
Literally, structure separated from skin, container separated from content.
That is, structure, skin and content should not be strongly coupled, but independent of each other, the goal to achieve is easier to reuse and combination, you can choose to use, choose to reference and so on.
Details about the link: www.smashingmagazine.com/2011/12/an-…
SMACSS — Scalable and Modular Architecture for CSS
In practice, OOCSS provides a useful idea, but SMACSS goes a step further in that it does not provide concrete implementation in terms of code organization.
Its core is:
A Base style is a set of generic styles that need to be defined first for a particular type of element.
例 句 : Layout style is related to the overall structure of the page, such as list, main content, location, width and height of the sidebar, Layout, etc.
The Module style is the Module that we extract and classify in the process of disassembly of the page, and this kind of style is written together separately.
Some elements on the page need to respond to different states, such as available, unavailable, used, expired, warning, and so on. Such styles can be grouped together.
5, Theme (subject) refers to the layout of the entire color, style and so on, general web site has not changed frequently larger, give us a deep impression is the QQ space, not many other applications, so, this does not generally used, but there is such a consciousness is good, when needed, just know how to plan.
With more than 5 classification strategy, we organize the code, the train of thought is clear, will arrange very orderly, another advantage is that can be solved after difficult and chaos, there are this problem, the main reason is that we don’t know how to standard belongs to define the elements and characteristics, the classification, we won’t name is random and chaotic, the basis, It’s easier and less likely to conflict.
For more information: smacss.com/
Third, Meta CSS
Atomic classes, also known as “semantically free” classes, look like this:
What are its characteristics? Style has nothing to do with structure or content. You define a set of rules in advance and add them where you need them. I’m sure when you first see this, you think, “How else can I write this? ! Yes, there are always some people, some new ideas and approaches, and this is one of them, not in terms of how good it is per se, of course, but the phenomenon and the process is good, and it’s often teased, like, “Is there a difference between this and inline?” “, “If you want to change the style, you have to change the HTML, maintenance is more difficult, also defeat the original intention of style and structure separation”, in fact, I personally do not agree with the above way of writing, if you want to remove these, then what can not be removed? And these properties, from project to project, from page to page, from module to module, don’t have a lot of universality, so it’s just a little bit lazy to pull them out, but in order to take care of more cases, you have to write redundant code, which is not worth the cost.
Although it has its disadvantages, I personally favor some other things to be separated out, such as: Float, text-align, Flexbox, etc. These are less likely values, and they are frequently used, easily reused, and rarely changed. In addition, you can extract other common small particle classes, such as the type of buttons, the type of text color, etc., which have nothing to do with CSS. Relevant to the project, this is about borrowing ideas from it, not directly using them.
Fourth, the BEM
Strictly speaking, BEM is not a fleshy set of patterns. It’s not just about how you plan at the CSS level. It’s an idea of how you organize, how you write code, and, decently simple, how it affects the front end.
Its core is as follows:
Block, Element, Modifier
It helps us define the level attributes of each part of the page and is, in a sense, a “tear down.” Naming rules are as follows:
Its appearance has brought inspiration to many people, but there are also some people who still hold a critical attitude, such as:
1, the style is not unified, the code is not clean and beautiful. 2, it may cause the class name is too long
Again, you don’t have to use it directly, but it has the advantage of letting you know what code belongs to a module and what it does just by looking at the class name. And then borrow from it.
Of course, BEM has been the work 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 your project, etc. Details can be consulted to the official website. Address: en. Bem. The info /
Realistically, it’s you who decides the outcome
How exactly do you use design patterns?
There are established design patterns, but in practice, you may feel that none of them fit perfectly for your project, or you may have to adjust them to use them at high cost. Actually, we don’t need to model, USES for to make model, you need to understand the principle behind them, want to know what they use what way to solve the problem, then draw lessons from it, use it to solve our problems, it is good, so you don’t need to give to not use, also don’t have to choose which, is not a simple say which is good, which is bad, There’s always something we can use it for. All rivers run into sea.
One of the things THAT I’ve been holding on to is that the front-end development troika — HTML, CSS, JS — is not, and cannot be, that good or that good in isolation. We rarely have code or modules that we use once, and we don’t write just one language. The troika works together. There are multiple factors involved in reuse, extension and teamwork, so you can’t just think, “I’m doing this right now, it’s unique, it’s fixed, it’s okay.” As a matter of fact, many problems are latent and should be viewed from the perspective of development. Between project documents, between projects, between team members, no matter what your division of labor is, you should consider the impact of the before and after and the possible inconvenience to cooperation.
What are the best practices? There is “best” only when there is “practice”. It is a castle in the air to talk about the best divorced from the actual situation. So, the best model is not a classic model, but in the process of the project, constantly running in and out of adjustment. Therefore, there is no need to be afraid of seemingly unknown design mode, and there is no need to be depressed because they do not understand the design mode, it is summed up by people’s actual combat method, you can also have your own mode ~