Appendix

CSS Preprocessing with LESS

It may seem a bit strange to talk about CSS in a JavaScript book, but preprocessing with LESS is hardly your standard CSS. LESS adds some of the familiar traits of a dynamic language that you can use to write efficient CSS, allowing you to compile your app's CSS with JavaScript. This preprocessor enables you to build CSS with variables, functions, and all the other features you've always wanted to use in CSS. LESS speeds up the development process and also makes stylesheets more organized and easier to maintain.

In this appendix, you find out why you should be using CSS preprocessing and how to install an automated LESS compiler. Then you learn the basics of LESS, including variables, operators, and nesting. You also discover how to use functions and custom mixins. Finally, you structure your LESS and organize it into separate files.

Introducing LESS

LESS allows you to script your CSS with custom variables and functions. Then the scripted LESS file is compiled to static CSS before it ever reaches the browser, which means you can use scripting in your CSS development efforts but still serve regular old browser-friendly CSS to your users. Additionally, if you decide to move away from LESS, you can simply start developing with the generated CSS file. Thus, there's really no loss to using a preprocessor.

What's So Good About Preprocessing?

CSS preprocessing has a number of advantages, all of which boil down to speeding up development and organizing stylesheets. The most impressive use case for preprocessing is how it handles CSS3 vendor prefixes. Without a preprocessor, you must memorize a number of different prefixes, some of which may use entirely different syntaxes. For example, take a cross-browser linear gradient:

.my-element {

  background-image:  -khtml-gradient(linear, left top, left bottom,

from(#444), to(#000));

  background-image: -webkit-gradient(linear, left top, left bottom,

color-stop(0%,#444), color-stop(100%,#000));

  background-image: -webkit-linear-gradient(top, #444, #000);

  background-image:    -moz-linear-gradient(top, #444, #000);

  background-image:      -o-linear-gradient(top, #444, #000);

  background-image:         linear-gradient(top, #444, #000);

  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#444444', endColorstr='#000000', GradientType=0 );

}

Here you see three different formats for the gradient: the older -webkit-gradient, the newer linear-gradient, and an IE fallback using filter. However, rather than memorize and type these different syntaxes, you can use a simple LESS mixin:

.my-element {

  .vertical-gradient(#444, #000);

}

As you can see, the LESS version is much easier to write. Of course, this is an exaggerated example, and you probably wouldn't include the –khtml-gradient for Konqueror or –o-linear-gradient for older versions of Opera. But chances are that you're using at least some vendor prefixes in your stylesheets. Think about how much faster and easier it would be to use LESS.

LESS isn't the only CSS preprocessor. Other popular options include SASS and Stylus.

Installing a LESS Compiler

Browsers don't understand the LESS syntax, so you need to compile it to standard CSS before deploying your stylesheets. Fortunately, a number of different compilers work on each operating system:

LESS.app for Mac OS X: First, if you're using Mac OS X, LESS.app is a very simple solution for LESS compilation. Download LESS.app from http://incident57.com/less. Open it and drag any LESS files/directories you want to watch into the app. Now, when you save a .less file, LESS.app automatically recompiles static CSS files.

SimpLESS for Windows and Linux: If you're using Windows or Linux, you can download SimpLESS, which works across all operating systems (including Mac OS X if you'd prefer it over LESS.app). Simply download the app here: http://wearekiss.com/simpless. Just like with LESS.app, all you have to do is drag and drop LESS files into the app, and it automatically compiles them to static CSS when a change is made.

Compiling on the Server

You can also set up your server to compile LESS at runtime or whenever a LESS file changes. In Chapter 7, you learn how to use the Express framework to compile LESS files automatically on a Node server. Otherwise, if you're using PHP you can leverage lessphp: http://leafo.net/lessphp/, or simply search for a compiler for any other platform you're using.

LESS Basics

Now that you have a compiler installed, you can start writing LESS. Open a file called style.less and add it to your compiler. In this section you'll learn how to use some of the most basic features of less: variables, operators, and nesting.

Variables

One of the simplest and most powerful features of LESS is the ability to use variables. Variables are defined with @—for example, you can create a variable for padding:

@padding: 25px;

.my-element {

  width: 250px;

  padding: @padding;

}

When this LESS file is compiled to CSS, the @padding variable will be inserted into the rule for .my-element.

When you define variables in LESS, you can also take advantage of scope. The previous example defined a variable at the top level, but you can also define local variables within any {} brackets. For example, you can overwrite the @padding variable:

@padding: 25px;

.my-element {

  width: 250px;

  padding: @padding;

}

.less-padding {

  @padding: 10px;

  

  padding: @padding;

}

.another-element {

  padding: @padding;

}

Here the original @padding is overwritten in the block for .less-padding, giving it a padding of 10px. But this doesn't overwrite the global @padding variable of 25px, which will still be used later in the .another-element block.

Operators

You can also use basic math operators in LESS; for example, you can combine the @padding variable with some basic math:

@padding: 25px;

.more-padding {

  padding: @padding + 10;

}

Here the .more-padding block gets a padding of 35px, or 25px + 10px. You can use any math operator you want: +, -, *, and /. And don't be shy about using operators with numbers—they're not only for calculating variable changes. Because the LESS file will be compiled to CSS, there's no loss in using these basic operators when you're too lazy to do basic math.

In fact, this can often be a better idea because the stylesheet will show why a particular number is that way—for example, when handling box-model issues:

.bordered-element {

  border-left: 1px solid black;

  border-right: 1px solid black;

  width: 250px - 1 - 1;

}

Here, instead of writing the ambiguous 248px, the block uses operators to show that the width is compensating for the two border widths.

Nesting

My personal favorite part of LESS is also the simplest. Nesting allows you to organize selectors under parent elements, making the stylesheet faster to write and a whole lot more organized. For example, without LESS, you might have a number of different rules for your site's header:

header {

  min-width: 800px;

}

header nav {

  width: 800px;

  margin: 0 auto;

}

header nav li {

  list-style: none;

}

header a {

  text-decoration: none;

}

But your LESS file can clean this up a lot by nesting each rule within its parent:

header {

  min-width: 800px;

  

  nav {

    width: 800px;

    margin: 0 auto;

    

    li {

      list-style: none;

    }

  }

  

  a {

    text-decoration: none;

  }

}

When this LESS file compiles, it looks exactly like the previous example, with all the parent rules written out explicitly. But nesting saves you the hassle of constantly having to retype parent selectors. Furthermore, it organizes the rules into more meaningful blocks, such as the header section in this example.

The new CSS3 spec allows for nesting in actual CSS files. But with cross-browser support still a long way off, it would be foolish to use this in your compiled stylesheets.

The & Symbol

So far you've seen nesting with parent-child relationships, but it can also be more versatile. You can use the & symbol to nest rules that are grouped, for example, without LESS you write this:

p {

  color: gray;

  padding: 10px;

}

p.more-padding {

  padding: 25px;

}

But you can use the & symbol to simplify this:

p {

  color: gray;

  padding: 10px;

  

  &.more-padding {

    padding: 25px;

  }

}

You can also use this with pseudo-classes—for example, to define a hover state for a link:

a {

  text-decoration: none;

  &:hover {

    text-decoration: underline;

  }

}

Furthermore, you can place the & symbol after a selector to reverse the parent-child order:

.child {

  color: blue;

  

  .parent & {

    color: red;

  }

}

This compiles as:

.child {

  color: blue;

}

.parent .child {

  color: red;

}

Nesting and Variable Scope

Variable scope becomes especially powerful with nesting because you can define a variable that is confined to the given block:

.contact-form {

  @labelWidth: 100px;

  @formPadding: 5px;

  

  padding: 5px 0;

  

  label {

    display: inline-block;

    width: @labelWidth - 10px;

    padding-right: 10px;

    text-align: right;

    vertical-align: top;

  }

  

  input[type=text], input[type=email] {

    width: 250px;

    padding: @formPadding;

  }

  

  textarea {

    width: 400px;

    height: 150px;

    padding: @formPadding;

  }

  

  input[type=submit] {

    margin-left: @labelWidth;

    font-size: 36px;

  }

}

Here the two variables @labelWidth and @formPadding are confined to the scope of this .contact-form block. This way, you can have site-wide @labelWidth and @formPadding variables that are set differently for this particular form.

Functions and Mixins

In addition to variables and basic operators, LESS supports a variety of more advanced functions you can use to streamline your CSS workflow. And where LESS doesn't have a built-in function, you can write your own.

Functions

LESS includes a number of prebuilt functions you can use to script CSS properties. For example, you can use the darken() function to darken the text of a link on hover:

a {

  @linkColor: #DDD;

  color: @linkColor;

  &:hover {

    color: darken(@linkColor, 20%);

  }

}

This will make the @linkColor 20 percent darker. Likewise, you can lighten() the color with lighten(@linkColor, 20%).

Most of the built-in LESS functions are color operations, but there are also some math functions, such as round(), floor(), and ceil(), as well as some miscellaneous functions. For a complete list of the functions available in LESS, visit: http://lesscss.org/#reference.

Mixins

Besides the standard LESS functions, you can create your own functions, called mixins. Writing your own mixins is really easy, and there are also a number of third-party mixins you can incorporate into your build.

Writing Mixins

One of the most common applications of mixins is handling browser prefixes for experimental CSS properties. For instance, even though border-radius is supported in most modern browsers, you can create a mixin to support older versions:

.border-radius(@radius) {

  -webkit-border-radius: @radius;

     -moz-border-radius: @radius;

          border-radius: @radius;

}

Next, call this mixin in a CSS rule:

.my-element {

  .border-radius(5px);

}

This will compile as:

.my-element {

  -webkit-border-radius: 5px;

     -moz-border-radius: 5px;

          border-radius: 5px;

}

You can also add a default to the argument that is passed into the mixin:

.border-radius( @radius: 10px ) {

  -webkit-border-radius: @radius;

     -moz-border-radius: @radius;

          border-radius: @radius;

}

Now, if you don't pass a radius value into the .border-radius() mixin, it will default to 10px. For more information on mixin-building techniques, visit http://lesscss.org/#-mixins.

Using Third-Party Mixins

Writing mixins is relatively simple, but that doesn't mean you should write them all yourself. LESS has been around for a while, and there are several free mixins you can use to jumpstart your LESS development. You can find these mixins through a search engine, or turn to the end of this chapter where I list a number of free mixins in the Further Resources section. Even if you'd rather write all your own mixins, these examples can be great starting points.

File Structure

Now that you know how to use the basic features of LESS, you're ready to put that knowledge into practice. But just like with other development efforts, it's a good idea to structure your LESS into separate files.

Using Imports

For example, you'll probably be reusing a set of standard mixins on every project. Copying and pasting these at the top of each LESS file doesn't make sense. Instead, place them in their own mixins.less file. Including the external file in your main style.less file is easy. Simply use @import:

@import "mixins.less"

This imports the LESS code in mixins.less into the current document.

Additionally, to import a file only if it hasn't been imported yet, use @import-once:

@import-once "mixins.less"

Finally, don't worry about HTTP requests when using @import—so long as the imported file has the .less extension, it will be concatenated into the parent file when LESS compiles.

Example File Structure

It's a good idea to use @import to break your LESS files into logical pieces. For example, your main style.less might look like this:

/**

* Import base variables

*/

@import "variables.less";

/**

* Import mixins

*/

@import "mixins.less";

/**

* Import other stylesheets

*/

@import "reset.less";

@import "site.less";

@import "media-queries.less";

Here the LESS file starts with base variables, a file that includes all the global variables you want to use throughout the stylesheets. Then it imports a standard set of mixins—for instance, those found on http://lesselements.com. It imports various stylesheets: a CSS reset such as the YUI reset, a set of main styles called site.less, and a set of modifications to the styles based on media queries.

Furthermore, note that there are no actual styles in the main style.less file. By storing all the styles in subfiles, you ensure that you can just copy style.less into any new project (as well as mixins.less and reset.less).

Customizing the Structure

You should customize the file structure to suit your individual needs and workflow. If you're embedding a number of different fonts with @font-face, include these in a separate fonts.less file. If a portion of your styling is pretty encapsulated, put it in its own file to make collaborative development easier.

Finally, match any organizational methods you're already using. For example, if you like to divide your styles into type, color, and layout, you can do so with separate files:

type.less for typography properties such as font-size

color.less for color and image properties such as background

layout.less for box-model properties such as width and padding

Summary

LESS streamlines front end development by bringing scripting into stylesheets. It not only speeds up the development process but also leads to better organized, easier-to-maintain stylesheets. In this appendix, you learned how preprocessing works and how to install a LESS compiler. Then you discovered the basics of LESS, including variables, basic operators, and nesting. Next you read about the LESS built-in functions as well as how to write custom mixins. Finally you found out how to structure the files in your LESS app to complement the organizational techniques you're already using. After seeing how LESS works, I'm sure you agree that it's a good idea to use CSS preprocessing for all your projects.

Additional Resources

LESS Documentation

http://lesscss.org

LESS Function Reference

http://lesscss.org/#reference

LESS Compilers

LESS.app (Mac OS X): http://incident57.com/less

SimpLESS (Cross-platform): http://wearekiss.com/simpless

Mod-less Apache Module: https://github.com/waleedq/libapache2-mod-less_beta1

Free Mixins

LESS Elements: http://lesselements.com

Useful CSS3 LESS Mixins: http://css-tricks.com/snippets/css/useful-css3-less-mixins

10 LESS CSS Examples You Should Steal for Your Projects: http://designshack.net/articles/css/10-less-css-examples-you-should-steal-for-your-projects

Tutorials

A Comprehensive Introduction to LESS Mixins: http://www.sitepoint.com/a-comprehensive-introduction-to-less-mixins/

How To Squeeze the Most out of LESS: http://net.tutsplus.com/tutorials/php/how-to-squeeze-the-most-out-of-less/

Mixins and Nesting: http://blog.lynda.com/2012/08/27/css-pre-processors-part-two-mixins-and-nesting/

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset