Go: Introduction to less CSS framework

Source: Internet
Author: User
Tags variable scope css preprocessor

Originally from: http://www.ibm.com/developerworks/cn/web/1207_zhaoch_lesscss/

Brief introduction

CSS (cascading style sheets) is a long-standing, markup language that, together with HTML, is widely used in the World Wide Web (Wide). HTML is primarily responsible for the definition of document structure, and CSS is responsible for the definition of document representation or style.

As a markup language, CSS syntax is relatively simple, the user's requirements are low, but also bring some problems: CSS needs to write a lot of seemingly illogical code, inconvenient maintenance and expansion, not conducive to reuse, especially for non-front-end development engineers, often because of the lack of CSS Writing experience and difficult to write well-organized and easy-to-maintain CSS code, the reason for these difficulties is because CSS is a non-procedural language, no variables, functions, scope (scope) and other concepts. Less is a boon for WEB developers, with the introduction of variables, Mixin (mixed), arithmetic, functions, and so on in CSS, which greatly simplifies the writing of CSS and reduces the cost of maintaining CSS, as its name says It allows us to do more with less code.

Back to top of page

Less principles and how to use them

In essence, less contains a set of custom grammars and a parser that defines their own style rules based on these syntaxes, which eventually generate the corresponding CSS file through the parser. Less does not cut the original CSS features, not to replace the CSS, but on the basis of the existing CSS syntax, for the CSS to add programming language features. The following is a simple example:

Listing 1. Less files
@color: #4D926F;  #header {   color: @color;  }  H2 {   color: @color;  }

The resulting CSS file is compiled as follows:

Listing 2. CSS file
#header {   color: #4D926F;  }  H2 {   color: #4D926F;  }

As you can see from the example above, learning less is easy, as long as you understand the basics of CSS, it's easy to get started.

Less can be used directly on the client or on the server side. In the actual project development, we recommend using the third method, compile the less file to build a static CSS file, and apply it in the HTML document.

Client

We can use the. Less source file directly on the client, just download the less.js file from http://lesscss.org and add the following code to the HTML we need to introduce the less source file:

<link rel= "stylesheet/less" type= "Text/css" href= "styles.less" >

Less source files are introduced in the same way that standard CSS files are introduced:

<link rel= "stylesheet/less" type= "Text/css" href= "styles.less" >

It is important to note that the Rel attribute is set to "Stylesheet/less" when the. less file is introduced. A more important point to note is that the less source file must be introduced before Less.js is introduced, so as to ensure that less source files are correctly compiled and parsed.

Server-side

Less on the server side is mainly the use of less compiler, the less source files compiled to generate the final CSS file, the current common way is to use node's Package Manager (NPM) installed less, after successful installation can be in the node environment for the less source files to be compiled Translated.

In the early stages of project development, we need to find ways to introduce our CSS or less files to our HTML pages or bridge files, regardless of whether we use the client or server side, less provides a feature-importing that we are familiar with. We can use this keyword to introduce the. less or. css file that we need. Such as:

@import "Variables.less";

The. Less file can also omit the suffix name, like this:

@import "Variables";

The introduction of CSS is just like the less file, except that the. css suffix name cannot be omitted.

Using compile-generated static CSS files

We can compile the less file into a CSS file using the less compiler, which is introduced into the HTML article. The point to be stressed here is that less is fully compatible with CSS syntax, which means that we can change the standard CSS file directly to the. less format, which the less compiler can fully identify.

Back to top of page

Syntax variables

Less allows developers to customize variables, variables can be used in global styles, and variables make it easier to modify styles.

We can understand the use and function of variables from the following code:

Listing 3 Less files
@border-color: #b5bcc7;  . Mythemes tableborder{    border:1px solid @border-color;  }

The resulting CSS file is compiled as follows:

Listing 4. CSS file
. mythemes Tableborder {   border:1px solid #b5bcc7;  }

As we can see from the code above, variables are reused at the value level, and the same values can be defined as variables to be managed uniformly.

This feature is useful for defining themes, and we can define general styles such as background color, font color, border properties, and so on, so that different themes only need to define different variable files. Of course this feature also applies to CSS reset (reset style sheet), in WEB development, we often need to block the browser default style behavior and need to redefine the style sheet to override the browser's default behavior, here you can use the less variable characteristics, so that you can reuse the style sheet between different projects, We only need to re-assign values to the variables on demand in different project style sheets.

The variable in less is the same as other programming languages, it can realize the reuse of the value, also it has the life cycle, that is scope (variable scope, developers are accustomed to call the scope), simple is the concept of local variables or global variables, the order of finding variables is first in the local definition, if not found, The parent definition is found until the global. Let's explain Scope by a simple example.

Listing 5. Less files
@width: 20px;  #homeDiv {    @width: 30px;    #centerDiv {        width: @width;//This should take the value of the most recently defined variable width 30px               }  }  #leftDiv {      width: @width;//This should take the top definition The value of the variable width 20px  }

The resulting CSS file is compiled as follows:

Listing 6. CSS file
#homeDiv #centerDiv {   width:30px;  }  #leftDiv {   width:20px;  }
Mixins (mixed)

Mixins (mixed) functionality is not unfamiliar to developers, many dynamic languages support the mixins (mixed) feature, which is an implementation of multiple inheritance, in less, which refers to the introduction of another defined class in one class, as in the current class Adds an attribute to the same.

Let's take a quick look at the use of mixins in less:

Listing 7. Less files
Defines a style selector. RoundedCorners (@radius: 5px) {  -moz-border-radius: @radius;  -webkit-border-radius: @radius;  Border-radius: @radius;  }  Use the #header {  . roundedcorners;  }  in another style selector; #footer {  . roundedcorners (10px);  }

The resulting CSS file is compiled as follows:

Listing 8. CSS file
#header {  -moz-border-radius:5px;  -webkit-border-radius:5px;  border-radius:5px;  }  #footer {  -moz-border-radius:10px;  -webkit-border-radius:10px;  border-radius:10px;  }

From the above code we can see: Mixins is actually a nesting, it allows a class to be embedded in another class to use, the embedded class can also be called a variable, simply speaking, mixins is actually a rule-level reuse.

Mixins also has a form called parametric mixins (mixed parameters), less also supports this feature:

Listing 9. Less files
Defines a style selector. Borderradius (@radius) {  -moz-border-radius: @radius;  -webkit-border-radius: @radius;  Border-radius: @radius;  }  Use the defined style selector #header {  . Borderradius (10px);//pass 10px as a parameter to the style selector}  . btn {  . Borderradius (3px);///Put 3p X passed as a parameter to the style selector}

The resulting CSS file is compiled as follows:

Listing 10. CSS file
#header {  -moz-border-radius:10px;  -webkit-border-radius:10px;  border-radius:10px;  }  . btn {  -moz-border-radius:3px;  -webkit-border-radius:3px;  border-radius:3px;  }

We can also define a one-person default value for the Mixins parameter, such as

Listing 11. Less files
. Borderradius (@radius: 5px) {  -moz-border-radius: @radius;  -webkit-border-radius: @radius;  Border-radius: @radius;  }  . btn {  . Borderradius;  }

The resulting CSS file is compiled as follows:

Listing 12. CSS file
. btn {  -moz-border-radius:5px;  -webkit-border-radius:5px;  border-radius:5px;  }

Like arguments in JavaScript, mixins has such a variable:@arguments. @arguments in Mixins is a very special parameter, when mixins reference this parameter, the parameter represents all the variables, in many cases, this parameter can save you a lot of code.

Listing 13. Less files
. Boxshadow (@x:0,@y:0, @blur: 1px, @color: #000) {  -moz-box-shadow: @arguments;  -webkit-box-shadow: @arguments;  Box-shadow: @arguments;  }  #header {  . Boxshadow (2px,2px,3px, #f36);  }

The resulting CSS file is compiled as follows:

Listing 14. CSS file
#header {  -moz-box-shadow:2px 2px 3px #FF36;  -webkit-box-shadow:2px 2px 3px #FF36;  box-shadow:2px 2px 3px #FF36;  }

Mixins is one of the most important features in less, and we've also written a lot of examples to see if you have a question like this: when we have a large number of selectors, especially when team co-development, how to ensure that the selectors between the name problem? If you are a Java programmer or C + + programmer, I guess you will think of the namespace namespaces,less also use the namespace method to avoid the name of the problem, and less on the basis of mixins to expand a bit, see the following a piece of code:

Listing 15. Less files
#mynamespace {  . Home {...}.  User {...}  }

So we've defined a namespace named MyNamespace, and if we're going to reuse the user selector, we just need to use it where we need to mix this selector. #mynamespace >. User.

Nested rules

When we are writing standard CSS, when we encounter multi-layered nesting of elements, we either adopt a nested definition from the outside to the inside, or take a CLASS or ID to a particular element. In less we can write:

Listing 16. HTML Fragment
<div id= "Home" >  <div id= "Top" >top</div>  <div id= "center" >  <div id= "left" >left</div>  <div id= "right" >right</div>  </div>  </div>
Listing 17. Less files
#home {    color:blue;    width:600px;    height:500px;    Border:outset;    #top {         border:outset;         width:90%;    }    #center {         border:outset;         height:300px;         width:90%;         #left {           border:outset;           Float:left;   width:40%;         }         #right {           border:outset;           Float:left;   width:40%;}}}  

The resulting CSS file is compiled as follows:

Listing 18. CSS file
#home {   color:blue;   width:600px;   height:500px;   Border:outset;  }  #home #top {   border:outset;   width:90%;  }  #home #center {   border:outset;   height:300px;   width:90%;  }  #home #center #left {   border:outset;   Float:left;   width:40%;  }  #home #center #right {   border:outset;   Float:left;   width:40%;  }

As we can see from the above code, the nesting rules for less are corresponding to the DOM structure in HTML, which makes our style sheet writing more concise and more readable. At the same time, nested rules make it easier to manipulate pseudo-elements.

Listing 19. Less files
a {  color:red;  Text-decoration:none;  &:hover {//have & parse is the same element or pseudo-class of this element, no & parsing is the descendant element  Color:black;   text-decoration:underline;  }  }

The resulting CSS file is compiled as follows:

Listing 20. CSS file
a {  color:red;  Text-decoration:none;  }  a:hover {  color:black;  Text-decoration:underline;  }
Operations and functions

In our CSS is filled with a lot of numerical value, such as color, padding, margin, etc., these values in some cases have a certain relationship, then how do we use less to organize the relationship between these values? Let's take a look at this piece of code:

Listing 21. Less files
@init: #111111;  @transition: @init  . Switchcolor {  color: @transition;  }

The resulting CSS file is compiled as follows:

Listing 22. CSS file
. switchcolor {   color: #222222;  }

In the above example, the use of less operation is a feature, in fact, simply speaking, is the numerical value (number, color, variable, etc.) to subtraction arithmetic. Less also provides a set of functions specifically for color operations. The following is a list of the functions provided by less for color operations:

Lighten (@color, 10%);//return a color which is 10% *lighter* than @color  darken (@color, 10%);//return a color whic H is 10% *darker* than @color  saturate (@color, 10%);//return a color 10% *more* saturated than @color  desaturate (@color, 10%);//return a color 10% *less* saturated than @color  Fadein (@color, 10%);//return a color 10% *less* tra Nsparent than @color  fadeout (@color, 10%);//return a color 10% *more* transparent than @color  spin (@color, 10); Return a color with a degree larger in hue than @color  spin (@color, -10);//return a color with a ten degree SMA Ller Hue than @color

PS: The above code is quoted from less CSS official website, please see http://lesscss.org/#-color-functions for details.

Use these functions in the same way that you use functions in JavaScript.

List less files
Init: #f04615;  #body {   Background-color:fadein (@init, 10%);  }

The resulting CSS file is compiled as follows:

Listing 24. CSS file
#body {   background-color: #f04615;  }

As we can see from the above example, this set of functions is like a function in JavaScript, which can be called and passed parameters. The main function of these functions is to provide the function of color transformation, the first color conversion to HSL color, and then to operate on this basis, less also provides a way to get the color value, here is not an example to illustrate.

The arithmetic and function features provided by less are suitable for implementing page component features, such as fade-in and fade-out during component switching.

Comments (note)

The appropriate annotations are the necessary means to ensure the readability of the code, and less provides support for annotations, mainly in two ways: single-line comments and multiline comments, as in JavaScript, where we do not give a detailed explanation, but only one point: single-line Comments (//single-line comments) is not displayed in the compiled CSS, so if your comment is for a style description, use a multiline comment.

Less VS SASS

Similar framework and sass:http://sass-lang.com/, compared with less, both belong to the CSS preprocessor, functionally similar, are the use of a program-like language to write CSS, have variables, mix, nesting, inheritance and other characteristics, the ultimate goal is to facilitate CS Writing and maintenance of S.

Less and SASS interact with each other, compared to more CSS syntax and more comparisons between the two, please refer to this post: https://gist.github.com/674726.

Back to top of page

Conclusion

This article refers to less basic functions, more advanced features such as: string interpolation, server-side use configuration, JavaScript expressions, avoid compiling, etc. can be see the official website.

Less on the basis of CSS syntax, but also borrowed a lot of our familiar with the programming language features, this for our developers to learn the cost can be almost ignored, it is to preserve the CSS syntax based on the expansion of more practical features, less provides us with a new style table method, We can choose to use less in accordance with our project characteristics, we can only use a very small cost to exchange a great return, in a word, less are more, with the help of more convenient Web development.

Reference Learning
    • Refer to the less official website to find out what is less.
    • Refer to W3Schools CSS to learn about CSS.
    • Refer to the SASS official website to find out what SASS is.
    • See Sass/less Comparison for Sass and less similarities and differences.
    • DeveloperWorks Web Development Zone: Extend your skills in web development with articles and tutorials dedicated to web technology.
    • DeveloperWorks Ajax Resource Center: This is a one-stop center for information about AJAX programming models, including many documents, tutorials, forums, blogs, wikis, and news. Any new Ajax information can be found here.
    • The DeveloperWorks Web 2.0 Resource Center, a one-stop Center for Web 2.0-related information, includes a large number of Web 2.0 technical articles, tutorials, downloads, and related technical resources. You can also quickly learn about the concepts of Web 2.0 through the Web 2.0 starter section.
    • Check out the HTML5 topic for more information and trends related to HTML5.
Discuss
    • Join DeveloperWorks Chinese community. View developer-driven blogs, forums, groups, and wikis, and communicate with other DeveloperWorks users.

Go: Introduction to less CSS framework

Related Article

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.