"Turn" is not so difficult, talk about CSS design patterns

Source: Internet
Author: User
Tags css preprocessor

What is design mode?

There have been jokes, design patterns are used by engineers to show off with others, appear tall, and some people say, not design mode useless, you have not been able to understand it, will use it.

Let's take a look at the official explanation: "Design pattern" is a set of reusable, most-known, categorized, code-design experience summaries. Design patterns are used in order to reuse code, make code easier for others to understand, and ensure code reliability. There is no doubt that design patterns in others in the system are multi-win; Design patterns make code production truly engineering; Design patterns are the cornerstone of software engineering, like the structure of a building. ”

Today we are going to talk about CSS design patterns.

Design patterns, this vocabulary we are common, almost all programming languages will have a few sets, but in-depth study of the few people, for the following reasons:

1, it seems that there is not much need to emphasize it, there are problems to change or according to team norms to do;

2, not to use some of the existing model is also harmless;

3, many people contact the business level has not reached the need to plan and organize the degree of light writing layout, write special effects, care compatible, enough to drink a pot of, no consciousness to think about some methodological issues.

Of course, all three of them are what I have experienced, I believe you are also ~

We will all grow up, will slowly do more, bigger, more complex projects, this time, we need top-down, the whole process to think about some problems. Backstage do not say, only the front-end, such as: Style, tone, module, layout, interaction, logic, and so on, if coupled with teamwork, if there is no plan, no matter how long, those seemingly no problem code, will expose a variety of problems, module naming, class naming, file organization, Common module extraction, code reuse, readability, extensibility, maintainability. They seem to be just some simple gestures, but you need to see farther, to avoid problems in the future need to pay a greater price, or even be forced to restructure the entire project, can be described as a work in the contemporary, the benefit of the generations ~

Now that you're designing a CSS, it's definitely a problem or a flaw in itself, and one of the most obvious is that any one of its rules is a global statement that will work on all the relevant elements of the page that introduces it, whether that's what you want. Independent and composable modules are the key to a maintainable system. below, we will discuss from a number of aspects, in the end how to write CSS, is more scientific.

Starting from demand

Score of

We have just started to learn to write, is not to consider, write out a word good or bad, the structure of the article is inappropriate, because we are not aware of. Write code is the same, just at the beginning, we just go to define the rules, can use the property, the syntax is correct, the page realized, just fine. Slowly, you will find that the page is also structured, we follow the structure of the page to organize the code, will it be better? For example, divided into head, navigation, sidebar, banner area, main content area, bottom and so on.

However, this seems to be enough, because there are some things, the reuse degree is very high, and it is not good to classify it as any inherent module, such as: bread crumbs, pagination, window, etc., they do not fit into a certain inherent module code, you can separate a section of the exclusive CSS and JS, perhaps, this is the origin of the component ~

Split

After the split, our code looks a lot better than before, the organization is clear, the maintenance greatly improved, but, as if still not enough, we will find something else, very small, but also very high reusability, they are also not suitable to be placed in the module, such as borders, backgrounds, icons, fonts, margins, layout and so on. If we define them once in each place where they are needed, they will be repeated many times, and it is clear that this deviates from good practice, resulting in code redundancy and maintenance difficulties. Therefore, we need to "dismantle". What happens after you've torn it apart? Where we want to use can be directly added, need to change the time unified change.

Row

After the "division", "Demolition", our code structure has been very clear, various content modules, functional modules, UI modules are well-behaved waiting for the call, then what is the difference? Yes, well ordered organization, clear classification, but also need to arrange orderly, never with the latitude to consider, we always strive for excellence. To raise a chestnut, 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 place different parts in a certain order, which makes our code look more orderly, easier to maintain, and facilitates inheritance or cascading overrides. Do not underestimate this step, seemingly dispensable, the actual requirements of a relatively high overall planning capacity, can reduce redundant code and quickly locate problem location.

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

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

2. Use block annotations

In the comments, you should try to detail the purpose of the code, State switching, adjustment reasons, interactive logic and so on, so that not only for their own maintenance, more conducive to others to take over to maintain your code.

Starting from the conclusion

In addition to some of the common parts of the requirements, there are other things that need attention but are not formally defined, and they derive from our practical experience, such as:

Level nesting not too deep

Know a little bit about the principle of browser rendering, it is in the parsing of CSS rules, it is from right to left, a layer of go to look for, if too many levels, will inevitably increase the rendering time, affecting rendering speed. Also, if you have too many selector levels, you may have an indirect response, and your HTML structure might not be as concise.

So exactly how many layers are appropriate? General advice is not more than 4 layers, but then again, more than 4 layers will be what? There will be no obvious impact, unless you write a very scary number, or the project is extremely complex, may be able to see the impact, in fact, from our daily needs, 4-storey can solve most of the problems, therefore, is reasonable.

Avoid using element selectors

For a two-point consideration:

1th , and the previous paragraph mentioned in the relevant, in the HTML, there are many common high-frequency elements, such as Div, p, span, A, UL and so on. If you use an element selector in the most inner layer of a multilayer selector, the browser iterates through all of the elements in the HTML when you start looking, obviously, this is not necessary.

2nd , our needs and code structure are there are potential changes, today wrote a page, tomorrow may have to add a button, add a sentence, and add in an icon. We write a structure that can be reused in other structures at any time. So, if you use an element selector to kill something, whether it's a new addition or something that's been added to another structure, it's highly likely to create a clash of styles, and at this point you have to write extra styles to overwrite the corrections, or redefine the class.

Therefore, for the above considerations, in the specific code module, try not to use the element selector, using the element selector premise is that you are completely determined, will not cause problems. Note that the scope I use is "specific code module", then the style used to define the general rule is OK, it is recommended, for example, reset. It can also be somewhere else, and it needs our own consideration.

Avoid using the group selector

What is wrong with group selector? Go straight.

This is a rare case, here is just an example, here is a three sets of selectors, to define the same style in different places, the obvious flaw is that if there is a fourth place to use, you have to add a group of selectors, if there are 10 different places, you write 10? This is very painful for the maintenance, the intelligent us, how can be so complicated and unnecessary labor, therefore, the wall crack does not recommend this approach, can be extracted out of a common class, define a unified style, and then, where to put where, reuse and maintenance will be more convenient.

Of course, you may say, when I write the first, I will not know that there are so many, there is no need to extract is not known, yes, so you need to judge according to experience, but also in the project to promote the process, the timely collation and refactoring of the code.

Number and order of file introductions

For the friend who just catenary page, these two points is also easy to neglect, because they seem to have no big impact, more than a few times the request, the style has loaded, are not so easy to drive people crazy. But in the extreme pursuit of user experience, we still hope that the number of file requests as little as possible, the content of the display has a priority order, file loading in a sequential order. In this way, when it is difficult to reduce the size of the file, let the user first see more important, normal display content.

These are just a few examples, more practical conclusions, we can read more relevant blog posts or books, will have the experience of the predecessors.

Starting from contradiction

General and Semantic

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

Naming conventions can help you immediately understand which category a particular style belongs to, and what it does within the overall scope of the page. In large projects, it is more likely to have styles broken in multiple files. In this case, the naming convention also makes it easier to find a file whose style belongs to which file.

Many times, we need a thing to be defined as universal, in order to reuse, such as: module title, button, hint text, icon, etc., at the beginning, we used to see the content of the visual manuscript, is "news", we define the "press", is "about", we define "about", is the red button, We define "RED-BTN" and so on, which can lead to a problem, if there is another style and structure similar to the news list, but not the news, how to do? The continued use of "news" is obviously inappropriate, which tells us that we cannot confine our attention to content and require separation of content and structure.

Can't use "news", then what? Abc? 123? This will not conflict, it's all right ~ In fact, this is the other extreme, so although to a large extent to avoid conflicts with other modules, but its own readability is greatly reduced, others, and even you yourself over a period of time will forget what it is, for team work is very bad. As to what kind of naming method you need, you need to plan according to the whole of the project, which is suitable for distinguishing the different structure according to the characteristics, and makes it easier to establish a connection between the name and structure, such as the category, function, page, etc.

Teams and individuals

A team, everyone's experience is different, coding level and habits are different, this will cause, a person a way of writing, you use the underline, I use the underline, I use English all spell, you use shorthand, and so on. While there are no right or wrong points, there are no small barriers to collaboration among team members, and others have to spend time adapting and understanding how you are organized and defined, which increases costs invisibly.

Therefore, there is the "team norms" exist in the necessary, the specification in addition to some of the wording of the provisions, so that our code more unified, clear, more readable, more discerning. It is also possible to extract some best practices and reusable modules that are good for everyone on the team.

Of course, for people, the most difficult is to adjust the existing habits, which will have to enter a team after the "transformation" of the pain, in fact, this pain is also a growing pains, you will learn better coding, better practices, from the project or the overall team to consider a matter of value and meaning.

CSS and pre-processors

I have the article in detail in front of the CSS preprocessor, I was also excluded from it, because of the cost of learning, because I feel that the application is not necessary. But once you decide to learn to use it, you will feel that it is not so, the preprocessor in introducing itself to you, it has been deliberately emphasized that its syntax is fully compatible with CSS, that is, you in less or sass file, directly write CSS code is no problem. In addition, it can provide us with a lot of convenience, such as defining a unified variable, using nesting instead of always repeating a few selectors, you can extract common blocks of code and then very convenient reuse and so on.

So, when we have the CSS organized and written well, the preprocessor is once again for us to plug in a pair of wings, can be more flexible and efficient coding.

Starting from the existing model

Let's take a look at some of the patterns that are widely circulated. (PS: Order and rank, good or bad)

First, oocss--object oriented CSS

Contact the computer should know, oop--object oriented programming, if you are first contact OOCSS, you will be very confused, is "object-oriented css"? It is not a real programming language Ah, how to object-oriented?

Oocss, first mentioned, was in 2009, and its two main principles were:

Separating structure from skins and container from content.

The literal translation comes from the separation of the structure and the skin, the container and the content.

That is, the structure and the skin and the content of the strong coupling, but independent of each other, to achieve the goal is more reusable and combination, can choose to use, select the reference and so on.

Learn more about Links: https://www.smashingmagazine.com/2011/12/an-introduction-to-object-oriented-css-oocss/

Ii. smacss--scalable and Modular Architecture for CSS

In practice, Oocss gives a kind of thought, but in the organization of the Code, it does not give the concrete implementation method, from this point, smacss further.

The core of it is:

1. Base (Base)

The underlying style is a generic fixed style that needs to be first defined for a class of elements.

2. Layout (layouts)

Layout style, is related to the overall structure of the page, for example, the list, the main content, the position of the sidebar, height, layout and so on.

3. Module (modules)

The module style, is that we in the process of disassembly of the page, the extracted categories of the module, this type of style is written together.

4. State (status)

Some elements in the page need to respond to different states, such as available, unavailable, used, expired, warning, and so on. This type of style can be organized together.

5. Theme (Theme)

Theme refers to the entire layout of the color, style and so on, the general site will not have frequent large changes, give us the impression of more deep is the QQ space, other applications are not many, so this generally will not be used, but there is such a sense is good, need to use the time, you know how to plan.

With the above 5-point classification strategy, our code is organized, the idea will be very clear, the arrangement is very orderly, the other advantage is that can solve the name and confusion, the reason why there is this problem, the main reason is that we do not know how to define the characteristics of the elements, after the classification, We will not be very random and chaotic to name, with the basis, it can be more relaxed, and not easy to conflict.

Learn more about Links: https://smacss.com/

Third, Meta CSS

An atomic class can also be called a "no semantics" class, like this:

What is the characteristic of it? Style and structure, content-independent, pre-defined so a set of rules, where needed to add, I believe everyone first saw this way of writing, will think: Still can write AH?! Yes, there are always some people, some new ideas and methods will emerge, it is one of them, of course, not to praise itself how good, but to say that this phenomenon and process is good, it itself is often spit, such as: "This writing and direct inline there is a difference?" "," If you want to adjust the style, it is necessary to change the HTML, maintenance more troublesome, but also against the style and structure of the original intention of the separation "and so on, in fact, I personally do not agree with the above this way of writing, if you want to pull out of these, then there is nothing to pull out of it? And these attributes, between the projects, between the pages, between the modules, and not too much commonality, pull these out, just a little lazy to save some effort, but in order to take care of more cases, you have to write redundant code, is not worth the candle.

Although it has shortcomings, I personally agree to some other things, such as: floating (float), text layout (text-align), flexbox layout, etc., These are not so many possibilities of value, and the use of frequent, reusable convenient, less change, in addition, You can also extract some other common small particles, such as the type of buttons, the type of text color, these and CSS itself is irrelevant, and project-related, which is to learn from its ideas, rather than directly to use .

Iv. BEM

Strictly speaking, BEM is not a model of bone and meat, and it is not only limited to the level of your CSS to plan, it is a way to organize and write the idea of code, and, seemingly simple, it has a huge impact on the front end of the world.

Its core is as follows:

Block (blocks), element (elements), Modifier (modifier)

It helps us define the level attributes for each part of the page, and in a sense, it's also a "tear-off". The naming rules are as follows:

It has been an inspiration to many people, but there are other people who still hold a critical attitude, such as:

1, the style is not uniform, the code is not neat and beautiful

2, may cause the class name too long

As I said earlier, you can not use it directly, but be clear about its advantages: It allows us to know what code is part of a module and what it does in a module only through the class name. then draw on it.

Of course, BEM gathered a lot of people's efforts, but also received a lot of praise, including the author of Oocss. So, it certainly is not so simple. It will also tell you how to write with JS, how your files are organized better, how the project should be built, etc. Detailed can go to the official website to consult. Address: https://en.bem.info/

From the reality, the person who decides the result is you.

How do you use design patterns?

Although there are already mature design patterns, in practice, you may feel that they do not exactly match your project, or that you are going to be able to adjust them to use them at a high cost. In fact, we do not need to cater to the pattern, to let the pattern for me, you need to understand the rationale behind them, to know what the way they solve the problem, and then use it to solve our problems , it is good, so do not need perplexed to use, do not need to tangle choose which, It is not simple to say which is good, which is bad, there is always a place where we can use it. Haina Rivers, set hundreds of people.

I personally have been insisting on another point of view is that the front-end development of the Troika--html, CSS, JS, do not, also can not be isolated to talk about that good or so good, we rarely have only one use of the code or module, and will not only write a language, the troika are working together, there will be re-use, There are many factors that extend and team work. Therefore, cannot hold the idea: I am doing this now, it is the only one, is fixed, no problem. In fact, a lot of problems are potential, to take the development of vision to see. project files, between projects, between team members, regardless of your division of labor, you have to take into account the impact and possible inconvenience to the cooperation.

What is best practice? There is "practice", only "best", from the actual situation to talk about the best, is the castles in the castle. Well, the best model, not which is the classic model, but in the project in progress, constant running-in adjustment. Therefore, do not need to be afraid of the seemingly unknown feeling of the design pattern, do not need to because they do not understand the design mode and depressed, it is people summed up the actual combat method, you can also have their own mode ~

Original address: http://kb.cnblogs.com/page/551422/

"Turn" is not so difficult, talk about CSS design patterns

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.