CSS code tips and Maintenance ★mozilla hacks–the WEB Developer Blog

Source: Internet
Author: User
Tags css preprocessor

Original link: https://hacks.mozilla.org/2016/05/css-coding-techniques/

Link: http://www.zcfy.cc/article/css-coding-techniques-x2605-mozilla-hacks-8211-the-web-developer-blog-1244.html

Recently, I've found that many people are stumped by CSS, both novice and experienced developers. Naturally, they want to have a better language to replace it, and the CSS preprocessor is born from this idea. Some people want to use CSS frameworks to write less code (we've seen in the previous article why this is not a good solution). Some people have begun to abandon CSS instead of using JavaScript to apply styles.

But you don't need to always use CSS preprocessor in your workflow. You also don't have to use a bloated framework as the default starting point for each of your projects. Any use of JavaScript to do some of the original CSS should do is a very scary idea.

In this article, we will see some tips and suggestions for better CSS, easier to maintain CSS code, so your stylesheet will become shorter and have fewer rules. CSS can be a handy tool instead of a burden.

Select the minimum available selector

##

CSS is a declarative language that you can use to specify styles for DOM elements. In this language, some rules take precedence over other rules, just as inline styles rewrite some of the previous rules.

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

  <button = "button-warning" >     
.button-warning { background: red;}button, input[type=submit] { background: gray;}

Although .button-warning button, input[type=submit] it was previously defined, it will still override the properties of the latter background . Why? What is the principle in deciding which rule will override the other one's style?

Accuracy.

Some selectors are considered more precise: for example, a selector #id overrides a .class selector. 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 this selector, we need a more precise ... Yes, it's just as a snowball rolls bigger and it gets harder to maintain in the end.

So, when you write your own selector, ask yourself: Is this the most appropriate selector?

All selector accuracy rules have been officially defined in the Web CSS specification, where you can find the details of each selector. If you want some more simple articles to help you understand, you can read this article.

Do not add more code to the bug

Let's consider a common scenario where you have a bug in your CSS and you've found out which DOM element has the wrong style. In addition, you find that it somehow has an inherently wrong attribute.

You may want to continue adding more CSS to it, and if you do, your codebase will get bigger and it will be more difficult to find bugs later.

Instead, look back for bugs and use your browser's development tools to see the elements and all the cascading relationships. Determine which rule is applying the styles you don't want. Modify the rules that already exist so that it does not result in unwanted results.

In Firefox, you can debug a style sheet by right-clicking on an element in a page and selecting it 检查元素 .

Look inside of it to see your cascading relationships (looks at that cascade in all it glory). Here you can see all the rules that are applied to the elements, in the order in which they are applied. The top rule is more accurate and can override the previous style. You can see that some of the attributes in some of the rules have strikethrough: this means that a more precise rule has been overridden for this property.

In addition, you can not only view these rules, in fact, you can choose whether to apply them, you can also modify them to observe the results, which is helpful to fix the bug.

The fix may be a rule change, or a change in the rules of another location in the cascade relationship. This may require a new rule. At the very least, you should know that this is the right thing to do, and that your code base is required.

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 reconstructed when necessary.

Do not use!important

The previous suggestion has actually hinted, but because of its importance, I want to emphasize it again: don't use it !important in your code

!importantis a feature in CSS that allows you to break cascading rules. CSS stands for "cascading style sheets", which is a hint.

!importantOften used when you are anxious to fix a bug, because you don't have enough time or don't want to fix the cascading relationship.

When you apply a property !important , the browser ignores the rule of precision. When you !important have a rule to rewrite another !important rule of the same, your big trouble comes.

In fact, there is a suitable use !important of the situation, is when you use the development tool debugging something. Sometimes you need to find a value that will fix your bug. Applying in your development tools !important to modify CSS rules can help you find the values you need without having to cascade features.

Once you know which CSS is working, you can go back to your code and see which layer of your CSS you should place on the layer.

More than pxAnd %

Using px (pixels) and % (percentages) units is very intuitive, so we will be looking at those little-known units here.

Emand rem

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

Let's consider the following HTML code:

<article>  Title <p>One Ring to bring them all and in the darkness bind the.</p></article>

Add the following rule:

article {  font-size: 1.25em;}

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

So h1 what about elements? To better understand what will happen next, let's add another CSS rule to the stylesheet:

h1 {  font-size: 1.25em;}

Even if it is 1.25em , and the element is the article same, however we must consider em the unity of the unit (compound). What do you mean? In other words, h1 as the immediate child element of the body, there will be a 20px font size ( 16*1.25 ). However, we h1 are located inside an element that has a font size different from the root element (our article element). In this case, the 1.25 font size given by the cascading relationship is referenced, so the h1 font size of the element will be 25px ( 16 * 1.25 * 1.25 ).

By the way, as a substitute for yourself to memorize these multiplication chains, you can use the Inspector tabs in the panel Computed , which shows the actual, final pixel values.

emThe unit is actually very practical, and it's easy to dynamically change the size of the page (not just the font size, but also some other properties such as line spacing and width).

If you like EM in relation to the basic size of the characteristics, but not like its complex. You can use rem units. The rem unit and em is very similar, but to remove its compound, just use the size of the root element.

So if we modify the units of the part of the CSS in front of us h1 em torem

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

vwAnd vh is the viewport unit. 1vwis 1% of the viewport width, which is also 1vh 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 useful because they do not always match the size of the body.

Other units

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

Using Flexbox

We have discussed this topic in the previous article on CSS frameworks, and the Flexbox module simplifies the work of layout and alignment of objects. If you don't know flexbox yet, check out this introductory article.

Yes, you can use Flexbox now, unless you really need to support those old browsers for some business reason. The current browser support rate for Flexbox is more than 94%. So you don't have to keep writing about those floating div s, how difficult it is to debug and maintain.

In addition, you should continue to focus on the latest grid modules, which will be as pleasant as the breeze.

When using CSS processors ...

CSS compilers such as sass or less are very popular in the field of front-end development. They are powerful tools, and if you make the most of them, you can use CSS more efficiently.

Do not abuse selector nesting

One of the more common features in these processors is the selector nesting, for example, the less code below:

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 abusing this feature is everywhere, and eventually the CSS selector repeats the entire DOM, so if we have the following HTML:

 <article class=  "POST" >  <!--...-->  span class= "tag" > <!--...--> </ARTICLE>              

We may find in the CSS stylesheet:

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

The main problem with these CSS rules is that they are very specific selectors. We already know this is what we are trying to avoid. There is also an over-nesting problem here. I've already discussed it in a different article.

In short, do not produce CSS nesting rules that you will never enter.

Include VS extension

Another useful CSS feature is mixed, which is a reusable CSS block. For example, if we want to apply styles to a button, and most of them have some basic CSS properties. We can also create a code that mixes in less like the following:

.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's very useful to reuse some common code.

In addition to the inclusion of a mixed, there is actually another option: "Extension" or to inherit it (the exact terms are different). All it does is merge multiple selectors into the same rule.

Let's take a look at an example of mixed use:

.button-Primary{ &:extend (. button-base)  background< Span class= "pun" >: Blue;}.-danger { &: extend (.  Button-base)  background : Red;               /span>                

This will be translated as:

.button-Primary, .button-Danger{ Padding: 1em; Border: 0; }.-primary { background : Blue;}.-danger { background : Red;               /span>                

Some articles on the web tell us that we only need to use "inclusions". Others, however, say the use of "extensions." The fact is that they produce very different code, in fact they are all fine, but depend on which of the processors you use more suitable.

I hope this will help you to re-look at your CSS code and write better rules. Remember what I said earlier: CSS is also code, so it's also worth paying attention to and maintaining your code base carefully. If you give it more love, you will certainly receive a return.

About Belén Albeza

Belén is an engineer and game developer and currently works with the Mozilla Development Alliance. She focuses on network standards, high-quality code, and game development.

    • Www.belenalbeza.com
    • @ladybenko

More articles by Belén Albeza ...

CSS code tips and Maintenance ★mozilla hacks–the WEB Developer Blog

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.