On the CSS Preprocessor (a): Why use a preprocessor

Source: Internet
Author: User
Background

Since the advent of CSS, the basic grammar and core mechanism has not changed in nature, and its development is almost entirely on the expressive level of ascension. The first CSS in the Web page function is only auxiliary decoration, light and easy to learn is the biggest demand, but now the complexity of the site is not the same, the original CSS has made developers powerless.

When the ability of a language is insufficient and the user's operating environment does not support other choices, the language is reduced to a "compile target" language. Developers will choose another more advanced language for development and then compile to the underlying language to actually run.

Therefore, in the front-end field, the sky down to the great people also, CSS preprocessor came into being. The old language of CSS, in another way, "re-adapted" to the needs of web development.

The preprocessor gives us the "super power"

With a simple comb, the CSS preprocessor brings us several important capabilities, which are listed below. (Do not care how much you use, regardless of the depth, is the benefit.) )

File segmentation

Page more and more complex, need to load the CSS file is also more and more large, we need to separate large files, otherwise difficult to maintain. The traditional CSS file segmentation scheme is basically a CSS native @import directive, or loading multiple CSS files in HTML, which are often not meeting performance requirements.

The CSS preprocessor extends the ability to @import instructions by consolidating the sliced files back into a large file through the compilation process. This solves the problem of inconvenient maintenance of large files, but also solves the problem of the performance of a bunch of small files at load time.

Modular

A step forward in the idea of file segmentation is "modularity". After a large CSS file is properly segmented, the resulting small file interrelationships should be a tree-shaped structure.

Tree-shaped root nodules are commonly referred to as "portal Files", and other nodes of the tree are generally referred to as "module files". A portal file typically relies on multiple module files, and each module file may also rely on other, more terminal modules to form the entire tree.

The following is a simple example:

entry.styl├─base.styl│   ├─normalize.styl│   └─reset.styl├─layout.styl│   ├─header.styl│   │   └─nav . styl│   └─footer.styl├─section-foo.styl├─section-bar.styl└─ ...

(The Portal file Entry.styl introduces the required modules at compile time, generates ENTRY.CSS, and is then referenced by the page.) )

If you have used other programming languages that have a modular mechanism, you should have realized that modularity is a very good way to organize your code and is an important tool for developers to design code structures. Modules can be clearly implemented code layering, reuse and dependency management, so that the development process of CSS can also enjoy the convenience of modern program development.

Selector nesting

Selector nesting is the way in which code is organized inside a file, which allows a series of related rules to be hierarchical. In the past, if we were to achieve this, we could only write:

. nav {margin:auto/* Horizontal center */; width:1000px; color: #333;}    . Nav li {float:left */* horizontally arranged */; width:100px;}        . Nav Li a {display:block; text-decoration:none;}

This kind of writing requires us to maintain the indentation relationship manually, and when the ancestor selector changes, all relevant subordinate selectors are modified, and it is not easy to write each rule in one line, and it is awkward to comment on a single statement (only between declarations).

In the CSS preprocessing language, the nested syntax can easily express the hierarchical relationship between rules, and it is clear and readable to write comments for a single statement:

. Nav    Margin:auto  //Horizontal Center    width:1000px    Color: #333    li        float:left  //Horizontal arrangement        width: 100px        a            display:block            text-decoration:none

Variable

Before the change occurs, all property values in the CSS are "magic numbers". You don't know how this value came from and what it means. With the variable, we can give these "magic numbers" a name, easy to remember, read and understand.

Next we will find that when a particular value is used in multiple places, the variable is a simple and efficient abstraction that can be eliminated and your code more DRY.

Let's compare the following two pieces of code:

/* Native CSS code */strong {    color: #ff4466;    Font-weight:bold;} /* */.notice {    color: #ff4466;}
Use Stylus to write $color-primary = #ff4466strong    color: $color-primary    font-weight:bold/* ... */.notice    color: $color-primary

You may have realized that variables make it easier for developers to unify the visual style of their website and make the need for "skin-changing" easier.

Operation

There is not enough light to have variables, we also need to have operations. If a variable makes a value meaningful, then an operation can associate a value with a value. The values of some properties are closely related to the values of other properties, which cannot be expressed by CSS syntax, whereas in preprocessing languages we can use variables and expressions to present this relationship.

For example, we need to have a container display at most three lines of text, which we used to write:

. wrapper {    overflow-y: hidden;    line-height:1.5;    max-height:4.5em;  /* = 1.5 x 3 */}

It can be found that we can only use annotations to express how the value of the max-height, and the comments in 3 such values are magic numbers, but also need further explanation. In the future, when the row height or the number of rows changes, the value of Max-height and the calculation in the comments also need to be updated synchronously, maintenance is inconvenient.

Next we use the preprocessing language to improve:

. wrapper    $max-lines = 3    $line-height = 1.5    overflow-y: Hidden    line-height: $line-height    Max-height:unit ($line-height * $max-lines, ' em ')

At first glance, the number of lines of code seems to be much greater, but the intent of the code is even clearer-the whole thing is clear without needing any comments. In post-maintenance, just modify those two variables.

It is worth mentioning that this notation also brings another benefit. $line-height This variable can be a. Wrapper a local variable (such as the above code) that is defined by itself, or it can be obtained from the upper scope:

$line-height = 1.5  //Global uniform row High body    line-height: $line-height.wrapper    $max-lines = 3    max-height:unit ($line-height * $max-lines, ' em ')    Overflow-y: Hidden

This means that. Wrapper can inherit row heights from their ancestors without having to write their own rows for this "show only three rows" requirement. With operations, we have the ability to express the association between attributes and attributes, which makes our code more flexible and DRY.

Function

By abstracting the usual operations, we get the function.

Developers can customize functions, and the preprocessor itself has a number of functions built into it. The most commonly used built-in function should be the color of the arithmetic function! With them, we don't even need to open Photoshop to color-tone, we can get a color of a tonal variant.

For example, we want to add a mouse hover effect to a button, and the simplest hover effect is to make the color of the button darker. The CSS code we've written might be something like this:

. button {    background-color: #ff4466;}. Button:hover {    background-color: #f57900;}

I believe that even the most senior visual designers can hardly distinguish between #ff4466 and #f57900 what is the relationship between the two colors. And if our code is written in a preprocessed language, that's a lot more intuitive:

. button    $color = #ff9833    background-color: $color    &:hover        background-color:darken ($color, 20%)

In addition, preprocessor functions often support advanced features such as default parameters, Mingshi arguments, arguments objects, and conditional branching can be set internally to meet complex logic requirements.

Mixin

Mixin is another useful feature provided by the CSS preprocessor. The form and usage of Mixin is very similar to a function--defined first, then called where needed, and parameters can be accepted at the time of invocation. It differs from a function in that a function is used to produce a value, and Mixin is the function of producing a piece of CSS code.

Mixin can produce multiple CSS rules, or it can produce only a few CSS declarations.

In general, Mixin can abstract a similar block of code from a CSS file and give it an intuitive name. For example, the CSS framework can wrap some commonly used code snippets as mixin, call them internally on demand, or expose them to the consumer at the business level.

For example, we often use clearfix to close a float. In native CSS, if you want to avoid clearfix code duplication, you can often only define a. Clearfix class, and then mount it to the desired element in HTML:

/* Define a class */.clearfix {...} for clearfix. Clearfix::after {...}
<!--attached to these two elements--><div class= "info clearfix" >...</div>...<footer class= "Clearfix" >...</ Footer>

Is it uncomfortable to expose the implementation of the performance layer to the structural layer? In the preprocessor, we can also choose another way of reusing:

Define a Mixinclearfix ()    for Clearfix ... &::after.        //called on the desired element. Info    clearfix () footer    Clearfix ()

Engineered

The CSS preprocessing language cannot run directly in the browser environment, which means that the source code we write will need to be compiled into CSS before it can be used for Web pages. This seems to be a threshold that requires us to pay "extra" costs.

However, in the current environment, most of the project's front-end development process has included a construction link, such as the choice of any one of the Scripting Modular scheme is required at deployment time to go through a wrapper. So for most teams, this threshold has actually more than half across the past.

And once we accept this setting, we can also enjoy the "extra" benefits. In the development of CSS to join the compilation process, but also to join other construction links, such as code validation, code compression, code post-processing and so on.

"Code post-processing" refers to the POSTCSS platform on the various types of plug-ins to provide the functionality, just autoprefixer this item is already worth back to the fare. We no longer need to manually add the browser prefix in the CSS code, directly using the standard notation, the rest of the tools to get it done!

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.