CSS Tutorials: Similarities and differences between less and sass

Source: Internet
Author: User
Tags filter format functions header variables php and string variable




Article Introduction: introduction of less and its difference with sass.




Original: introduction of less and its difference with sass
Translated from: An Introduction to less, and Comparison to Sass
Original Author: Jeremy Hixon
Please respect the copyright, reproduced please indicate the source, thank you!


Since I stumbled upon less one months ago, I've started to use it firmly. CSS itself is never a problem for me, but I'm curious about the idea of using variables to create something for my Site or template along a palette. Having an optional color plate with a fixed number of options allows me to avoid the color jumping so much that it is detached from an established style.









It turns out that less--and sass--functions are much more than that. Less and sass have some grammatical similarities, such as the following:


    • mixed class in (mixins)--class;
    • parameter is mixed --class that can pass parameters, just like functions;
    • Nested rules --class class in order to reduce duplicate code;
    • Mathematics is used in the operation --css;
    • Color Function --can edit color;
    • namespace (namespace)--grouping styles, which can be invoked;
    • Scope --local modification style;
    • JavaScript Assignment --use JavaScript expressions in CSS to assign a value.


The main difference between less and sass is how they are implemented, LESSS is based on JavaScript, so it's handled on the client.



Sass, on the other hand, is based on Ruby and is then processed on the server side. Many developers do not choose less because the JavaScript engine requires extra time to process the code and then output the modified CSS to the browser. There are many ways to do this, and I choose to use less only in the development segment. Once I have completed the development, I will copy and paste the less output into a compressor and then go to a separate CSS file to replace the less file. Another option is to use Less.app to compile and compress your less files. All two options will minimize your style output to avoid any problems that may arise from a user's browser not supporting JavaScript. Although this is not possible, it is possible after all.



Less is more



Introduced



The introduction of less in your project is simple:


    1. Download less.js;
    2. Create a file to put your style, such as style.less;
    3. Add the following code to your HTML

<link
			rel= "stylesheet/less" type= "Text/css" href= "styles.less"
			>
<script
			"src=" Less.js "
			type=" Text/javascript "></script>


Notice the link's Rel property. You need to use/less on the last side of the attribute value to make the less work. Then it is also necessary to introduce scirpt behind link. If you're using HTML5 grammar-why not? You can save Type= "Text/css" and Type= "Text/javascript".



There is actually a server-side less version . The easiest way to install less on a server is to use Node Package Manager (NPM, which is known to be based on Node.js).



Variable



If you are a developer, the variable should be your best friend. If you want to use a message repeatedly (in this case, color), set it to a variable. In this way, you can guarantee your consistency and may reduce the scrolling code to find the color value, copy, paste and other tedious work. You can even add or subtract some of the hex values you need to render to these colors. Look at the example:


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


If we apply these styles to 3 div, we can see the effect of the gradient created by the added and lost hex values:



Gradient effects from @light_blue to @blue to @dark_blue



The only difference between a variable in less and sass is that less uses $ for @,sass. There are also differences in scope, which I will mention later.



Mix (mixin)



Occasionally, we create style rules that will be reused in style sheets. No one will stop you from using more than one class in an HTML element, but you can use less to do it in a style sheet. To illustrate this point, I wrote a few examples:


 
. border
					{
	border-top:
					1px
					dotted
					#333;
}
Article.post
					{
	background:
					#eee;
	border;
}
Ul.menu
					{
	background:
					#ccc;
	border;
}


This gives you the same effect as the two elements that you add to the bordered class--and it's just done in the style sheet. And it works very well:



Text and unordered lists are used with border styles



In Sass, you add a @mixin declaration before the style rule to specify that it is nested. Then, call it through @include:


 
@mixin Border {
	border-top:
					1px
					dotted
					#333;
}
Article.post
					{
	background:
					#eee;
	@include border;
}
Ul.menu
					{
	background:
					#ccc;
	@include border;
}


Parameter mixed



Like functional functionality in CSS, these are useful for work that is redundant in today's CSS work. The best and most useful example is the private prefix of many browsers we are experiencing from the CSS2 to the CSS3 transition process. Nettuts+ has a very good video and article written by Jeffrey Way, which contains files made up of useful parameters that cover most of the CSS3 properties that use the private prefixes of each browser. For example, in their format, a simple mixin that handles rounded corners is like this:


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


In this example,. Border-radius has a default 3px fillet, but you can use any value you need. Border-radius (10px) will generate rounded corners with a radius of 10px.



The syntax in sass is much like less, just using $ to declare variables, and then using the aforementioned @mixin and @include to invoke.



Selector inheritance



This thing less is not provided. With this feature, you can attach a selector to a previously defined selector without having to use commas to separate the two:


 
. menu
					{
	border:
					1px
					solid
					#ddd;
}
. Footer
					{
	@extend. menu;
}
 
* * The above rules and the following effect is the same: */
. menu,
					. footer
					{
	border:
					1px
					solid
					#ddd;
}


Nesting rules



Nesting classes and IDs in CSS is the only way to avoid disturbing your style or interfering with other styles. But it could be messy. Using a selector similar to #site-body. Post. Post-header H2 is unattractive and takes up a lot of unnecessary space. With less, you can nest IDs, class, and tags. For the example mentioned earlier, you can write this:


 
#site-body
					{.....
	Post
					{...
		. Post-header
					{...
			.. H2 {...}
			A {...
				.. &:visited {...}
				&:hover {...}}}
			}


The code above is the same as the previous example (the long list of selectors), but it's much easier to read and understand, and it takes up very little space. You can also use the & to refer to the element style to their pseudo element, which is similar to this in JavaScript.



Operation



This may be what you expect: use numbers or variables to implement math 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;


I also realized that I could divide 4来 to get the @quarter_page variable, but here I just wanted to demonstrate that the "order of operation" of the parentheses is also available here. In the use of shorthand rules, parentheses are also required, such as border: (@width/2) solid #000.



Sass is more professional than less in numbers. It can already be converted into units. Sass can process unrecognized units of measure and output them. This feature is clearly an attempt at the future-proving some of the changes that have been made by the consortium.


 
/* Sass/
2in
					+
					3cm
					+ 2pc = 3.514in/
 
* Less/
2in
					+
					3cm
					+ 2pc = Error


Color function



At the beginning of the article, I mentioned how less helped me handle the coding process around a palette. One of the biggest contributors to this is the color function. Join you with a standard blue to run through your style, and then you want to use this blue in the form to make a gradient button. You can turn on Photoshop or some other editor to get a lighter or darker hex color value as a gradient. Alternatively, you can just use the color function in less.


 @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); }


The lighten function obviously reduces the color by a percentage value, which in this case reduces the base's blue 10%. This method allows us to change the color values of the elements or any other element--simply changing the base color. This is useful for themes (templates). And, if you use the parameter function, as mentioned above, you can also be more simple to apply to some browser private prefix declarations, such as:. Linear-gradient (Lighten (@blue), @blue, 100%);.



Well, the end result is really awesome:



Nice gradient, variable-based "Submit" button.



There are many other color functions, such as darkening or adjusting the saturation of the color, and even you can rotate the color plate to use other colors. I suggest that I try what you can think of (usage) in person.



Sass seems to have more options--but I don't need that much. My personal most often is lighten and darken. If you want to know more, you can look at this very detailed introduction .



Conditional Statement and Control



This is a really good thing, but also another less does not support the function. Using Sass, you can use the IF {} else {} Conditional statement and the for {} loop. It even supports and, or and not, as well as 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;}
}


Name Space (namespaces)



Namespaces can be used to organize our CSS to another level, and we can group some common styles and use them directly when we use them. For example, if we create a style group named default, we can call it directly from that group when we use it.


 
#defaults
					{
	. Nav_list
					()
					{
		list-style:
					none;
		margin:
					0;
					padding:
					0;
	}
	. Button
					()
					{...}.
	Quote
					()
					{...}}


Then, in our code, if we just use the UL element in a NAV element, we think we need the default style. Then we can simply call it, and it will be applied directly.


 
Nav ul {
	#defaults > nav_list;
}


Scope



Scopes are standard in programming, as are less. If you declare a variable at the root level of your stylesheet, it can be used throughout the document. However, if you redefine the variable in a selector, such as ID or class, then it will only be available in this selector-and, of course, the redefined new value.


 
@color: #00c; /* Blue/
#header
					{
	@color: #c00/* Red/
	border:
					1px
					solid
					@color;/* Red Border * *
}
#footer
					{
	border:
					1px
					solid
					@color;/* Blue border */
}


Because we have redefined the color variable in #header, the value of the variable will be different and will only be valid in that selector. All the places before or after it, if not redefined, will keep the original value.



Scopes are slightly different in sass. In the code above, when the @color variable turns red, the value of the variable after this here is rewritten (red).



Comments



This part is based on comparison. Two types of annotation are allowed in less. Standard CSS Annotations,/* Comment * are valid, and can be processed and correctly exported. When the line annotation,//comment, can also be used but not through processing can not be output, and then, the result is, "silent."



Import



The import is also fairly standard-compliant. Standard @import: ' classes.less '; Handled very well. However, if you want to import other less files, the file name extension is optional, so @import ' classes '; is also feasible. If you want to import some content that does not need less processing, you can use the. css extensions (e.g., @import: ' reset.css ';).



String insertion



A string can also be used in a variable and then invoked by @{name}.


1
2
@base_url: "Http://www.qianduan.net";
Background-image:
					url ("@{base_url}/images/background.png");


Escape (escaping)



You may occasionally need to introduce a value that is illegal or less unrecognized in a CSS. It is usually a hack of some ie. To avoid throwing exceptions and destroying less, you'll need to avoid them.


 
. class
					{
	filter: ~ "Progid:DXImageTransform.Microsoft.Alpha (opacity=20)";
}
 
/* The following code will actually be output:/
. class
					{
	filter:progid:DXImageTransform.Microsoft.Alpha (opacity=20);
}


JavaScript Assignment



This is my favorite part of less: using javascript--in the stylesheet is pretty exciting. You can use an expression, or you can refer to the direction of the environment to use inverted single quotes.


 
@string: ' Howdy '. toUpperCase () '; * * @string become "HOWDY" * *
 
you can also use the above mentioned interpolation: * *
@string: "HOWDY";
@var: ~ ' @{string} '. Topuppercase () '; /* to "HOWDY"
 
////* Get the information of the document * * *
@height = ' document.body.clientHeight ';


Output format



However, less does not have output settings, while Sass provides 4 output options: Nested, compact, compressed and expanded.



Conclusion



The two methods have a lot in common. They are all very useful tools for writing code designers, and they can also help developers work more efficiently and quickly. If you are a fan of Ruby or Haml, then sass will be your good helper. For me, a PHP and JavaScript geek, I tend to less because it makes it easy to introduce and use JavaScript expressions and document properties. I suspect that I'm even closer to really understanding the possible programming in a stylesheet, but I still keep trying. If you're working with one or two of them, I'd love to hear more about it and see your results. Of course, tips, tricks, corrections are always welcome.



There are some hasty translations, and if there are any mistakes or improper places, please point out. Mixin This word, here literally "mixed", but the feeling is not too appropriate, check for a long time also did not see a very suitable translation, here to reach the person pointing. In addition, for some reason, lesscss.org seems to be inaccessible in your country, you can directly access less warehouse on git,http://github.com/cloudhead/less.js, The wiki for the project also has the same documentation as the official website, which can be read in detail. --God Fly




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.