The difference between less and sass

Source: Internet
Author: User
Tags script tag

This article comes from ThoughtWorks Jing Ren, thanks to Jing Ren translation (Chinese version, English original). I feel very ashamed, a bit of stealing the act, so I must declare again from our lovely Jing Ren, and once again thank her for the painstaking.

If you are still in front of the web for CSS design, maintenance, development puzzles, I think you can try less or sass alternative dynamic CSS system.

The original text reads as follows:

Since I started using less a few months ago, I've written a big fan of it. CSS has never been a problem for me, but I'm fascinated by the idea that less can set the colors of a theme into variables to keep my site consistent in style. It's like we have a palette with a couple of colors on it, and we can choose from it without getting mad at the color and not straying from the track.

Less and sass, there are more things to do. They have a lot in common, like, say:

Blending (mixins)-Classes for Classes

mixed with parameters (parametric mixins) -Classes to which you can pass parameters, like functions.

nested Rules (Nested rules)-class nesting class to reduce duplicate code

Operations (Operations)-calculations in CSS

color Functions -used to modify colors

Namespaces (namespaces)-group styles, and can be accessed through group names

Scope-temporary modifications to a style

JavaScript Evaluation (JavaScript evaluation) -executing javascript expressions in CSS

The biggest difference between less and sass is the way they handle it. Less is a JavaScript library, so it executes on the client.

And, Sass, you need Ruby to run on the server side. Many developers do not choose less because it takes additional time for JavaScript to parse less code to return CSS code in the browser. There are several ways to avoid this problem. One is to use less only in the development phase. Once the development is complete, I translate the less into CSS code, put it in another file, and refer to the CSS file where I refer to the less file. Another approach is to use Less.app to compile and minimize your less files. Both of these methods can reduce the impact on style and prevent browsers from running problems with JavaScript. Although the possibility is very small, but it is always possible.

Update: The above discussion has sparked a lively debate, even on Twitter. Please also consider Adam Stacoviak's reply "The reality is that Sass needs Ruby, but it does not necessarily translate to CSS on the server side." It can be compiled locally (as less claims), and the compiled CSS can be used like the previous CSS. Because this is smashing Magazine, there must be a lot of readers, and I guess a lot of the readers here are using Mac to read this article. Then, all Mac computers support Ruby by default, so installing and running SASS requires only one command line (sudo gem install sass).

Once you install the sass, you can compile the sass into CSS locally and refer to the CSS in your project. If you don't know how to start using Sass (or Compass) then you can read this article: "Getting Started with Sass". Thank Adam for pointing out the problem.

Less is more

installation

It's very easy to use less on your project:

1. Copy Less.js

2. Create a style sheet, such as style.less

3. Add the following code to the HTML

<link rel= "stylesheet/less" type= "Text/css" href= "http://anotherwayaround.blog.163.com/blog/styles.less" >
<script src= "Http://anotherwayaround.blog.163.com/blog/less.js" type= "Text/javascript" ></script>

Note the ref attribute of the link label. You need to end with "/less" to work. Immediately after the link tag, include the script tag. If you are using HTML5 syntax, then you can remove type= "text/css" and Type= "text/javascript" sentences.

There is also a server-side less. The easiest way to use less on the server side is to use node Package Manager (NPM).

Variable (Variables)

If you are a developer, the variable is your best friend. When you need to use the same information more than once (such as font, color), it is reasonable to set it as a variable. This method ensures consistency and does not have to rummage through files to find a hexadecimal digital copy and paste. You can even add and subtract this hexadecimal number. For example:

@blue: #00c;
@light_blue: @blue + #333;
@dark_blue: @blue-#333;

If we apply these 3 colors to the three Div, we can see a color gradient effect:

The order of application is: @light_blue, @blue, @dark_blue

The only difference between less and sass defining variables is that less uses $ for @,sass. There are also different scopes, which I will briefly explain later.

Mixing (mixins)

Sometimes, we want to create some styles that we can reuse throughout the stylesheet. You can add the same class to these elements in HTML, and you can do this by using less and just modifying the CSS. For example, there are two elements on the page that use one of the same style:

. border {
border-top:1px dotted #333;
}

Article.post {
Background: #eee;
. border;
}

Ul.menu {
Background: #ccc;
. border;
}

The above code, which implements and adds class ". Bordered" to both elements in HTML, does not require you to modify the HTML. The effect is also very good:

All two elements have a border-top style.

In sass, you need to first define a style using @mixin. Then, use @include to invoke it:

@mixin Border {
border-top:1px dotted #333;
}

Article.post {
Background: #eee;
@include border;
}

Ul.menu {
Background: #ccc;
@include border;
}

Mixing with parameters (parametric mixins)

It's as if using function in CSS helps to optimize those seemingly repetitive CSS. One of the most useful examples is that in the process of using CSS3, some styles need to use different prefixes to support different browsers. Nettuts+ has a very good article, Jeffrey Way, wonderful webcast and article, which describes a number of CSS3 methods to solve common mixins attribute prefix problems. For instance, for the simplest rounded corners:

. Border-radius (@radius: 3px) {
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
Border-radius: @radius;
}

In this case,. Border-radius This class has a 3px rounded corner by default, and you can also pass in other values when you call, and if you use. Border-radius (10px), then the rounded corners are 10px.

The syntax in SASS is similar to that in less, except that you use $ to define variables and first use @mixin to define a style. Then use @include to invoke it.

Selector Inheritance (Selector inheritance)

This is a function that less does not have. with this feature, you can use the @extend method to add a selector style to another selector.

. menu {
border:1px solid #ddd;
}

. footer {
@extend. menu;
}

* Would render like so: * *
. menu,. footer {
border:1px solid #ddd;
}

Nested rule (Nested rules)

The nested class and ID in CSS are the only way to solve the interaction between styles. But it's a hassle to write. Like using one of these selector

#site-body. Post. Post-header H2

It's very unpleasant, and it's a waste of space. With less, you can nest Id,class and elements more efficiently. Like the example above, you can write this:

#site-body {...

. Post {...

. post-header {...

H2 {...}

a {.....

&:visited {...}
&:hover {...}
}
}
}
}

This code is the same as the ugly CSS code above, but it is easier to read and takes up less space. Also, you can use the & notation to refer to the current element as this in JavaScript.

Operation (Operations)

You might expect to have a function that calculates constants or variables in your stylesheet.

@base_margin: 10px;
@double_margin: @base_margin * 2;

@full_page: 960px;
@half_page: @full_page/2;
@quarter_page: (@full_page/2)/2;

For @quarter_page This variable, I know I can divide it directly by 4, but I would like to take this opportunity to illustrate the use of parentheses, which are also applicable here for the rules used to adjust the order of execution. If the style contains more than one attribute, the parentheses are required, for example: border: (@width/2) solid #000.

Sass is more powerful than less in calculating numbers. It is internally self-contained with a different unit of the conversion table. Sass can calculate an unknown unit of measure and print out the results. This feature is apparently introduced in a attempt to future-proof the library against changes by the.

* Sass * *
2in + 3cm + 2pc = 3.514in

* Less * *
2in + 3cm + 2pc = Error

colour method (color functions)

We mentioned earlier that less helped me figure out a color combination. This feature is part of the color method. Suppose, in your style, to use a standard blue, you want to use this color on a "submit" button and make a gradient effect. You can turn on Photoshop or some other image editor to get to the darker or lighter blue that the blue gradient requires, and you can use the color method provided by less directly:

@blue: #369;

. Submit {
padding:5px 10px;
border:1px solid @blue;
Background:-moz-linear-gradient (top, lighten (@blue, 10%), @blue 100%);/*moz*/
Background:-webkit-gradient (linear, center top, center bottom, from (Lighten (@blue, 10%)), Color-stop (100%, @blue)); webkit*/
Background:-o-linear-gradient (top, lighten (@blue, 10%) 0%, @blue 100%); /*opera*/
Background:-ms-linear-gradient (top, lighten (@blue, 10%) 0%, @blue 100%); /*ie 10+*/
Background:linear-gradient (Top, lighten (@blue, 10%) 0%, @blue 100%); /*w3c*/
Color: #fff;
text-shadow:0 -1px 1px rgba (0,0,0,0.4);
}

This lighten method can be used to make a certain color variable as a percentage. In the code above, it lightens the standard blue 10%. This method allows us to easily change the color of the gradient elements, but also can easily change the base color. This is a great help for our support of multiple topics. In addition, if you use a method with parameters, as in the example above, you can encapsulate the browser prefix in a method so that you can simply write this:

. Linear-gradient (Lighten (@blue), @blue, 100%);

You can get an effect like this:

There are many other ways to change the depth of the color, saturation, and even turn it into another color. I suggest you try it out for yourself and see what you can do.

Sass seems to offer more color options--but I don't often use them. Getting deeper and lighter is the most common method I use. For more details, refer to this article: in-depth article on the topic.

conditional Statements and controls (conditionals and control)

This is a great feature, but less doesn't support it. using SASS, you can use the IF {} else {} statement, and you can use the for{} loop. It also supports and,or and not keywords, and also supports operators such as,,, <=, >=, and = =.

/* Sample Sass "If" statement * *
@if lightness ($color) > 30% {
Background-color: #000;
} @else {
Background-color: #fff;
}

/* Sample Sass "for" Loop * *
@for $i from 1px to 10px {
. border-#{i} {
border: $i solid blue;
}
}

Namespaces (namespaces)

We can use namespaces to organize style hierarchies, less allows us to create a set of styles that are often used and can be invoked elsewhere. For example, we create a set of styles called defaults, which can be taken from the group when some elements need to be used.

#defaults {
. Nav_list () {
List-style:none;
margin:0; padding:0;
}
. button () {...}
. quote () {...}
}

In the following code, if there is a NAV element in the UL need to use a default style, we simply call it can be:

Nav ul {
#defaults > Nav_list;
}

Scope (SCOPE)

Scopes are important in the programming process as well as in less. If you define a variable at the root level, you can call it anywhere in the document. If you define a variable with the same name in a selector, it overwrites the superior variable, and it is only in this selector that the value is fetched.

@color: #00c; * Blue */

#header {
@color: #c00; /* Red *

border:1px solid @color; * would have a red border * *
}

#footer {
border:1px solid @color; * would have a blue border * *
}

Because we have redefined this variable in #header, the value of this variable in this selector is different from the outside. Calls that precede and after this selector retain the outer values.

Less is a bit different to the processing of scopes and sass. For the above code, once the @color becomes red, then all subsequent code will be interpreted as red.

Note (Comments)

This section is very basic and less supports two types of annotations. Standard CSS Annotation,/* Comment * *, it can be processed by less and output. Single NOTE://comment, but not output, so this annotation is "silent".

Import (Importing)

Importing is also a necessary feature. Standard @import: ' classes.less ' can work under less. If you are importing a less file, the suffix name can be omitted, so it can be written as @import ' classes '. If the file you want to introduce does not need to be less, then you need to write a suffix name, such as. css (for example: @import: ' Reset.css ').

String insertion (interpolation)

You can insert a string variable in a style:

@base_url = ' http://coding.smashingmagazine.com ';
Background-image:url ("@{base_url}/images/background.png");

Escape (escaping)

This escape function is important if you want to use an illegal CSS syntax, or less syntax that is not recognized. Typically, using this feature is to do a crazy Microsoft Hack. To avoid less throwing exceptions, you need to escape them:

. class {
Filter: ~ "Progid:DXImageTransform.Microsoft.Alpha (opacity=20)";
}

/* would actually be outputted lik

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.