Xu Haoxing, front-end engineer of Wedoctor Front-end Technology Department. An ambitious young man who thinks the joy of life lies half in stillness and half in motion!

Writing in the front

Start to ask you a question: who are the front three swordsmen?

Needless to say, most front-end development comes off the top of your head: HTML, CSS, and JavaScript. If this also need to hesitate, friends to reflect on their own corner [manual dog head]. Since it is called the three Musketeers, it means that these three play an important role in front-end development. HTML is responsible for the construction of the page structure, CSS is responsible for the layout and beautification of the page, and JS is responsible for giving static pages to dynamic logic. From this point of view, all three are really indispensable. However, as business requirements tighten, we often fail to achieve the “rain and rain”, consciously or unconsciously neglecting a role – CSS.

For example, IN my daily business development, I often pay attention to THE HTML structure and JS logic, and become indifferent to CSS. The result is that when pages are interactive and styled, we write too many lines of CSS and never want to look at them again. In emotionally intelligent terms, we write CSS code that is very challenging for subsequent developers to maintain.

When I calmed down, I dissected the reason carefully and found that it was mainly due to the high stability of the style code. Once you’ve written your CSS, it’s almost impossible to change it later. This kind of “one-time” very difficult not to let a person take a little confused “mentality” to develop, and then leave a pile of mess to the back of the colleagues scold 🤬.

But! The way of Heaven is good reincarnation! If you encounter the need to modify CSS styles written by others, then this is a nightmare 👿. It’s hard not to doubt life and finally choose to rewrite it (whoo-hoo, stop scolding, stop scolding)! After encountering this situation, I realized that we need to guide CSS writing as a whole to make style files beautiful! That’s why I wrote this article.

First, CSS and aesthetics

Aesthetics is subjective and influenced by various factors, such as cultural background, knowledge system, personality and hobbies. As front-end developers, we often deal with aesthetics in programming. Sometimes we often say that such and such code to write garbage, read a long time also do not understand. Big guy code is unbeatable, clear and logical. These comments on code are a reflection of our aesthetic perception.

CSS exists to give a page beauty, as you can see in the following GIF:

The above GIF I think every user would prefer to add CSS files after the page, because it conforms to the aesthetic taste of people.

Since CSS can make pages more beautiful, we should make CSS more beautiful.

Second, what kind of CSS is popular?

We’ve already found our purpose: to make CSS look good! So what’s the purpose of looking good? It’s likeable. Let’s not resist modifying the original code while developing the requirements. Which begs the question: What kind of code is so resistant to change? Let’s look at the following two types of CSS code:

Personally, at first glance, the code on the left appears to be “crowded” and messy. The code on the right is clearer and more comfortable with empty lines between blocks. So the question is, why does the code on the right make me feel better? After carefully comparing the two pieces of code, I found the answer:

  1. Each piece of code is spaced so that it doesn’t give you a very big idea.
  2. Level control is limited to 3 levels to avoid “disgusting” people with too many nested levels
  3. It follows the BEM naming convention, potentially conveying hierarchy between elements

It all boils down to this: break your code’s logical concerns into chunks that multiple developers can easily digest, and make sense of themselves. This process reduces the amount of logic your brain has to deal with, and makes it feel good!

So let’s go a little further and abstract out the writing principles of CSS.

3. Some writing principles of CSS

CSS itself has no built-in organization and is written in a variety of ways, such as inline and inline. So we need to do the work of establishing consistency and regularity when writing CSS. The Web community already has a variety of tools and methods to help developers manage large CSS projects. We can borrow and adapt it to our own style of writing. But before we do that, we need to clarify a few CSS writing principles.

  1. Less is more
  2. Since the interpretation
  3. reusable

The above three principles were developed by myself during the development process. If you have more ideas 💡, please feel free to discuss them with me. Let’s start with the first rule: Less is more. The English version of this sentence is the view of architect Van der Rohe in the field of architecture. He objected to the fussy and meaningless decoration of products made by machinery. The same applies to CSS writing. In the front three, HTML is structure, JS is behavior, and CSS is presentation. In other words, CSS is used to decorate the page. In this context, eliminating redundant CSS code not only reduces browser performance but also allows developers to think more deeply about the relationship between presentation and structure. I think this is helpful for the growth of the mind of the front-end developer.

// There is redundant code.footer {
  margin-top: 30px;
  margin-bottom: 20px; } / / optimization.footer {
	margin: 30px 0 20px 0;
}
Copy the code

The code above is the simplest practice of less is more, but it’s not limited to that. We need to think and practice in a holistic way. So how do you do this? Without it, but the hand is familiar. So in every development, remember our motto: “Never write one more line of CSS!” .

The second principle of self-interpretation means that CSS should be written as clearly as possible to explain what it is doing and to reduce the amount of extra comment code.

// There are ambiguities.footer:first-child {
  color: #FFF;
  font-size: 18px; } / /.footer-title {
  color: #FFF;
  font-size: 18px;
}
Copy the code

The code above explains the purpose of this element, which is the text for title in the footer section. This allows us to easily locate the corresponding HTML element and make style changes. For the implementation of this principle, the community has a very complete scheme: BEM naming. This specification not only avoids naming conflicts between different files, but also makes CSS class names semantically. Let our minds clear up the vague image of CSS.

<div class="person-center__wrap"> <div class="person-center__main"> <div class=" userinfo-name "> <div > <div Class ="userinfo-age"> 24 </div> </div> <div class="person-center__footer"> <div class="sctions-comfirm"> </div> </div>Copy the code

The above code uses BEM naming to cram extra page structure information into the CSS class name so that developers don’t get confused about the CORRESPONDING DOM structure of the CSS. Coupled with the pre-processing language SASS, more from the mind will eliminate the CSS information lack and ambiguity, to ensure the unity of the page structure, performance and behavior.

The last principle of reuse is not to be discussed, but to be understood. The basis for this principle is the use of a CSS preprocessor language. Because CSS itself is a description language, it has no logic. But as businesses get more complex, we’re eager to add logical code to CSS. This is one of the reasons for the rise of SASS preprocessor languages. By adding logic to the CSS preprocessor language, we can define variables, use loops, and conditional judgments to reuse CSS code.

4. Tips for keeping CSS clean

Now that we know the principles for writing CSS, we need to apply them in practice. In this process, some tips for keeping CSS clean are helpful to practice.

1. Determine the code specification for the project

When working on a project with multiple people, the first thing you need to do is check that the project has a CSS code specification. Developing according to the code specification of the project is the foundation of keeping CSS clean and protected from ridicule. If your personal preferences conflict with the norm, follow the norm anyway, as others may not like your style.

2. Be consistent

When you start developing requirements and writing CSS code, it’s important to keep everything uniform. For example, the previous code used REM units and began with a conversion and variable definition. Then all you need to do is follow!! Rather than using a different set of their own way.

Uniformity is useful everywhere, such as using the same naming convention for classes, choosing a way to describe colors, or maintaining a uniform format (such as do you use tabs or Spaces to indent code? If it’s code, how many?

By following a set of rules all the time, you can save yourself a lot of mental overhead when writing CSS, because some decisions are already made. Remember that code is written for people, and can be run on machines by the way.

3. Format the CSS in a readable format

You can see a lot of CSS formatting. Some developers put all the rules in one line, like this:

.box { background-color: # 567895; }
h2 { background-color: black; color: white; }
Copy the code

Other developers prefer to put everything on a new line with empty lines between different elements:

.person-center {
  &-wrap {
		width: 100%;
  }
  
  &-main {
		color: #FFF;
    font-size: 16px;
    font-weight: 500; }}Copy the code

CSS doesn’t care which way you format it. My idea is to make CSS code readable while following code specifications. Make sure you want to look at it again, so that other developers can look at your code.

4. Comment your CSS

The code is self-explanatory, but some custom requirements need to be commented to indicate the relevant business context and other information. Not only will this help any future developer with your CSS files, but it will also help you get back into the game when you leave the project for a while.

/* This is a CSS comment that can be broken up into several lines. * /

Copy the code

It’s a good technique to put a comment between logical paragraphs in your stylesheet. These comments can help you quickly locate different paragraphs as you zoom in, and even give you keywords to search for or jump to that CSS section. If you use a string does not exist in the inside of the code, you can jump between from paragraph to paragraph, you just need to search for, below we use is | |.

/* || General styles */./* || Typography */./* || Header and Main Navigation */.Copy the code

Maybe you’re following a community tutorial, and CSS is a little less intuitive. At this point, you should include the tutorial URL in the comments. You should revisit your project a year or more from now, but only vaguely remember that you had a great tutorial and don’t know where it was, and thank yourself for adding comments.

5. Add logical paragraphs to your stylesheets

It’s a good idea to style general things first in a style sheet. This is all the styles that will work broadly, unless you want to do something specific to an element. Typically, you can set rules for the following elements:

  • body
  • p
  • h1, h2, h3, h4, h5
  • Ul and ol
  • Table attributes
  • link

In this style sheet, we provide default styles for site types, setting up a default style for tables, lists, etc.

/* || GENERAL STYLES */

body{... }h1.h2.h3.h4{... }ul{... }blockquote{... }Copy the code

After this section, we can define some utility classes, such as a class to remove the default list style, which we intend to display as flexible style or something else. If you know things that you want to apply to many different elements, then you can add them here.

/* || UTILITIES */

.nobullets {
  list-style: none;
  margin: 0;
  padding: 0; }...Copy the code

We can then add anything that will be used throughout the site, which could be things like basic page layout, headers, or navigation bar styles.

/* || SITEWIDE */

.main-nav{... }.logo{... }Copy the code

Finally, we can add specific things to CSS, breaking them up into contexts, pages, and even the components they use.

/* || STORE PAGES */

.product-listing{... }.product-box{... }Copy the code

By laying out our code in this way, we can at least get a rough idea of what parts of the stylesheet we can look for to change.

6. Avoid too specific selectors

If you create very specific selectors, you will often find that you need to reuse a piece of code in your CSS to apply the same rules to other elements. For example, you might have code like the selector below that applies the rule to

with the box class in

with the main class.
article.main p.box {
  border: 1px solid #ccc;
}
Copy the code

If you later want to apply the same rule somewhere outside of Main, or somewhere outside of

, you may have to add another selector to those rules, or create a new rule. Alternatively, you can create a class called Box and apply it anywhere.

.box {
  border: 1px solid #ccc;
}
Copy the code

Making things more specific sometimes makes sense, but this is generally the exception rather than the practice.

7. Split large stylesheets into smaller stylesheets

This is a technique that we’ve done pretty well. A common project has a styles file that stores globally shared style files. These files are subdivided into reset.csss, variables.less and so on according to their function. With the pre-processing language’s mixin functionality, we can maintain a common style file and avoid writing verbose CSS code on specific pages.

This makes it easier to keep your CSS organized, and it also means that if you have multiple people writing CSS, you’re less likely to have two people writing the same style sheet at the same time, preventing conflicts in source control.

8. Use tools

One thing that distinguishes humans from gorillas is their ability to use tools to solve our problems. In the wave of the Internet, we should embrace those helpful tools 🔧. Use stylelint + Githook to standardize our CSS code, and Less/Sass preprocessor language to make CSS more “logical”. They free up our brains, and they nurture our coding norms in a subtle way.

9. Learn and imitate

No one is perfect. One advantage of human beings is that they can improve themselves through learning. Then we, as programmers, need to exchange experience with excellent peers and learn from others’ good coding specifications into our daily development. Everyone is an independent individual, everyone also has their own ideas, in this line, open mind, used to admit their own shortcomings, is the source of eternal progress!

This includes thematic discussions between offline teams and online community discussions. Only by communicating with others can we broaden our technical horizon.

Writing code is a conversation with yourself

Forgive me for summarizing a very artistic title at the end. Recently I was watching a pretty old Japanese drama: “Dragon Sakura”, in which the hero Abe Hiro told several “fools” who were preparing for the exam that the exam was a dialogue with themselves, but also a dialogue with their competitors.

When we enter the workplace, whether we are full of passion at the beginning of the workplace or the fluctuations after several years of training, we are limited to affect only ourselves. But the information cocoon not only closes our knowledge of the outside world, but also deprives us of our knowledge of ourselves.

Stretch the time scale to one year, three years, five years, 10 years. The code you write is always there as an anchor point in time. Isn’t that a different kind of dialogue between the future and the present? So how do you organize CSS? The first rule is to use it as a conversation with yourself, so that you don’t feel bad about yourself. On this basis, master and find your own coding principles, use specifications and tools to correct and monitor yourself, and the rest is an infinite cycle of practice => modify => practice again => modify again.

Clean code is written by clean people, and it must be a lovely person to write lovely code. I started coding with the ideal of using the virtual world to help me understand the complexity of the real world. We’re evolving complex, confusing CSS code into clean code with clear logical concerns. This process is also a dialogue with yourself, asking yourself what you like and what you want. In this subconscious question after question, we organize our minds.

We are in the world of 0 and 1, thinking about the joys and sorrows of the physical world, hope that friends can skim the floating foam brought by the floating world, can find the true meaning of life! After all, hard work is only the means, our goal is a happy life in the future! All of you!