CSS code skills and maintenance Mozilla Hacks the Web developer blog

CSS code skills and maintenance Mozilla Hacks the Web developer blog

Recently, I found that many people are stumped by CSS, whether they are novices or experienced developers. Naturally, they hope to have a better language to replace it, and the CSS preprocessor was born from this idea. Some people wanted to use CSS framework to write less code (we have in the previous article to see why this is not a good program). Some people have begun to abandon CSS and use JavaScript to apply styles.

But you don't need to always use CSS preprocessors in your workflow. You don't need to use a bloated framework as the default start of every project. Anyone using JavaScript to do something CSS should do is a terrible idea.

In this article, we will see some tips and suggestions for writing better CSS, CSS that is easier to maintain codes that , so your style sheets will become shorter and have fewer rules. CSS will become a convenient tool rather than a burden.

Choose the smallest available selector

##

CSS is a declarative language, with which you can specify styles for DOM elements. In this language, some rules take precedence over others, just like inline styles overwrite some previous rules.

For example, if we have the following HTML and CSS code:

 class="button-warning"> 
.button-warning {
  background: red;
}

button, input[type=submit] {
  background: gray;
} 

Although it .button-warningwas button, input[type=submit]previously defined, it still overrides the latter's backgroundattributes. why? What principle is deciding which rule will rewrite another style?

Accuracy .

Certain selectors are considered more precise: for example, a #idselector will override a .classselector. What happens if we apply a more precise selector than it actually needs? If we want to rewrite these styles later, we want to rewrite the selector just now, we need a more precise...yes, it's like a snowball that gets bigger and bigger and eventually becomes harder to maintain.

Therefore, when you write your own selector, ask yourself: Is this the most suitable selector ?

All the selector accuracy rules have been officially defined in the W3C CSS specification . You can find the details of each selector here. If you want some simpler articles to help you understand, you can read this article .

Don't add more code to the bug

Let us consider such a common situation: there is a bug in your CSS, you have found which DOM element has the wrong style. In addition, you also find that it somehow possesses a property that it shouldn't have.

You may want to continue to add more CSS to it. If you do this, your code base will become larger and it will be more difficult to find bugs in the future.

As an alternative, look back for bugs and use your browser's development tools to view the elements and all the layered relationships. Determine which rule is applying the styles you don t want. Modify the existing rules so that it does not produce undesirable results.

In FireFox, you can debug the style sheet by right-clicking on an element in a page and selecting it.

Look at that cascade in all its glory in it. Here you can see all the rules that are applied to the element, in the order in which they are applied. The top rule is more accurate and can rewrite the previous style. You can see that some attributes in some rules have strikethroughs: this means that a more precise rule has overridden this attribute.

In addition, you can not only view these rules, in fact, you can choose whether to apply them or not, you can also modify them to observe the results, which is very helpful for fixing bugs.

The repair method may be a rule change, or a rule change elsewhere in the cascading relationship. This may require a new rule. At least you should know that this is the correct requirement and is required for your code base.

This is also a good time to refactor the code . Although CSS is not a programming language, you should give it the same consideration as JavaScript or Python: it should be clean and readable. Therefore, it should be refactored when necessary.

Don't use !important

There is actually a hint in the previous suggestion, but because of its importance, I want to emphasize it again: don t use it !importantin your code

!importantIt is a feature in CSS that allows you to break the cascading rules. CSS stands for "Cascading Style Sheets", which is also a hint.

!important It is often used when you are anxious to fix a bug, because you do not have enough time or do not want to fix this cascading relationship.

When you apply an attribute !important, the browser will ignore the accuracy rules. When you use !importantone rule to rewrite the other, there is also!important when rules, your big trouble came.

In fact, there is also a suitable use !importantcase, that is, when you use development tools to debug something. Sometimes, you need to find out which value can fix your bug. Apply !importantto modify the CSS rules in your development tools , which can help you find the values you need regardless of the cascading features.

Once you know which CSS can work, you can go back to your code to see which layer of the cascade relationship you should put your CSS on.

Only pxand%

The use of px(pixels) and %(percentages) units is very intuitive, so we will focus on the lesser-known units here.

Em and rem

The most famous relative unit is em. 1em is equal to the font size of that element.

Let us consider the following HTML code:


  

Title

One Ring to bring them all and in the darkness bind the.

Add the following rules:

article {
  font-size: 1.25em;
} 

Most browsers will apply a 16px font size to the root element by default (by the way, this feature can easily be overridden). So the article element above will have a font size of 20px ( 16*1.25).

What about the h1elements? In order to better understand what will happen next, let's add another CSS rule to the style sheet:

h1 {
  font-size: 1.25em;
} 

Even if it is 1.25em, and articleelements of the same, however, we must consider the emcomplex of units (compound). What does that mean? In other words, h1as a direct child of body, there will be a 20px font size ( 16*1.25). However, ours h1is inside an element with a different font size than the root element (our articleelement). In this case, the 1.25reference is the font size given in the cascading relationship, so h1the font size of the element will be 25px ( 16 * 1.25 * 1.25).

By the way, instead of memorizing these multiplication chains by yourself, you can use the Inspectortab in the panel Computed, which displays the actual, final pixel value.

emThe unit is actually very practical, by using it you can easily dynamically change the size of the page (not only the font size, but also other properties such as line spacing and width).

If you like the characteristics of em relative to the basic size, and don't like its complex nature. You can use remunits . remThe unit sum emis very similar, but its complexity is removed and only the size of the root element is used.

So if we modify the unit in our previous CSS h1part emtorem

article { font-size: 1.25em; }
h1 { font-size: 1.25rem; } 

vw and vh

vwThe sum vhis the viewport unit. 1vwIt is 1% of the viewport width, which is 1vhalso 1% of the viewport height. When you need a UI element to occupy the entire screen (such as a traditional translucent mask layer), they are very useful because they will not always be the same size as the body.

Other units

Other units may not be as common or useful as the ones above, but you will definitely encounter them someday. You can learn more about them in detail (on MDN) .

Use flexbox

We have in a previous article about CSS framework of discussed this theme, flexbox module simplifies the work layout and align objects. If you are not familiar with flexbox, check out this introduction article .

That's right, you can use flexbox now, unless you really need to support those old browsers for some commercial reasons. The current browser support rate for flexbox is more than 94% . So you don't need to continue writing those floating divs, how difficult they are to debug and maintain.

In addition, you should continue to pay attention to the latest Grid module , which will be as pleasant as a breeze.

When using a CSS processor...

CSS compilers such as Sass or Less are very popular in the field of front-end development. They are extremely powerful tools, and if fully utilized, you can use CSS more efficiently.

Don't abuse selector nesting

In these processors, a more common feature is selector nesting, for example, the following Less code:

a {
  text-decoration: none;
  color: blue;

  &.important {
    font-weight: bold;
  }
} 

Will be translated into the following CSS rules:

a {
  text-decoration: none;
  color: blue;
}

a.important {
  font-weight: bold;
} 

This feature allows us to write less code and better organize the rules to be applied to the elements that are usually together in the DOM tree. This is also very useful for debugging.

However, the phenomenon of abuse of this feature can be repeated everywhere, and finally the entire DOM is repeated in the CSS selector. Therefore, if we have the following HTML:

 class="post">
  
    
    

Tags: href="..." class="tag">irrelevant

We may find in the CSS style sheet:

article.post {
 //... other styling here
  header {
   //...
    p {
     //...
      a.tag {
        background: #ff0;
      }
    }
  }
} 

The main problem is that these CSS rules are very specific selectors . We already know that this is something we try to avoid. There is also a problem of excessive nesting. I have discussed it in another article .

In short, don't produce CSS nesting rules that you will never enter yourself .

Contains VS extension

Another useful characteristic of CSS is mixed , it is a reusable piece of CSS. For example, suppose we want to apply styles to a button, and most of them have some basically the same CSS properties. We can also create a mixin in Less like the following code:

.button-base() {
  padding: 1em;
  border: 0;
} 

Then, create a rule like the following:

.button-primary {
  .button-base();
  background: blue;
} 

This will generate the following CSS:

.button-primary {
  padding: 1em;
  border: 0;
  background: blue;
} 

As you can see, it is very useful for reusing some common code.

In addition to "containing" a mixin, there is actually another option: " extending " or inheriting it (the exact term is different). What it does is merge multiple selectors into the same rule.

Let's look at an example of using mixins:

.button-primary {
  &:extend(.button-base)
  background: blue;
}

.button-danger {
  &:extend(.button-base)
  background: red;
} 

This will be translated as:

.button-primary, .button-danger {
  padding: 1em;
  border: 0;
}

.button-primary { background: blue; }
.button-danger { background: red; } 

Some articles on the Internet tell us that we only need to use "include". Others, however, say that "extensions" are used. The fact is that they produce completely different codes. In fact, they are not problematic , but depend on which processor you are using is more suitable.


I hope this helps you re-evaluate your CSS code and write better rules. Remember what I said earlier: CSS is also code, so it is also worthy of attention, and carefully maintain your code base. If you give it more love, you will surely receive it in return.

About Bel n Albeza

Bel n is an engineer and game developer, currently working with the Mozilla Development Alliance. She is concerned about the development of network standards, high-quality code, and game development.

More articles by Bel n Albeza