Book Image

Learning less.js

Book Image

Learning less.js

Overview of this book

Table of Contents (22 chapters)
Learning Less.js
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Why you should use Less


We've already seen that Less is designed to help make CSS easier to manage and maintain. Let's explore some of the key features in more detail, which will give you a taste of what to expect with Less and demonstrate how Less can make writing CSS easier.

Reducing redundancy with variables

How many times have you worked on a website where you needed to declare the value of a color in CSS, such as #ececec? 10 times? 20 times? It's rare that you will get the color in the first time; it is more likely that you will need to revise it, which can create a real burden when working in CSS. No matter how many times it ends up being, one thing is true: it is not easy to remember the hex value for each color.

Less can help by allowing us to define colors as variables, with more memorable names. A variable is merely a mechanism for referencing a value; take a look at the following three examples:

@red: #de1446; 
@blue: #4a14de; 
@green: #32de14;

The beauty of Less is that once we've defined these variables, Less will automatically update any instance where they are used if we decide to change the hex values at a later date.

Understanding the syntax of variables

In Less, the @ sign indicates that we are defining a variable; following this (@) symbol, we normally have the name of the variable (with no spaces), and the colon indicates the end of the variable name. This is followed by the value, with a semicolon used to close the statement. In this case, the @red variable refers to the red color we want as a hex value. Once we've defined these variables, we can use them anywhere in our Less style sheet shown as follows:

.red-box {
  color: @red;
}

When we compile it, the following valid CSS is produced:

.red-box {
  color: #de1446
}

Note

In Less, compile just means to go from Less to CSS. We will use this term frequently throughout the book.

Writing and remembering variable names is far easier than remembering unnatural hex values, right? Moreover, when these values need to change, we only need to update them in one location and Less takes care of updating everything else. No more need to perform a "find and replace" when changing colors—this can be a huge timesaver!

Creating reusable blocks of code

So we've created some variables…but reusable blocks of code?

One of the benefits of using Less is that we can group together multiple lines of code and turn them into a reusable block that we can drop in our code. Let's take a look at an example:

.serif() {
  font-family: Georgia, 'Times New Roman', serif;
}

This is a very simple example of a reusable block of code, or mixin. If you've spent any time developing JavaScript or jQuery, then you may recognize a similar behavior in the form of classes; mixins work in pretty much the same way.

Mixins, by themselves, won't do anything and to make them useful, we need to call them from our code using a placeholder, as highlighted in the following code:

p {
  font-size: 10px;
  line-height: 1.25em;
  .serif;
}

This compiles to valid CSS:

p {
  font-size: 10px;
  line-height: 1.25em;
  font-family: Georgia, 'Times New Roman', serif;
}

See how, with just one short keyword, we've asked Less to drop in something more involved? One small point to note is the use of () against the mixin name—Less will compile the reusable code (or mixin) to valid CSS, but it will not render the compiled mixin on the screen. The great thing though is that we can simply call .serif; wherever we need to render text using the defined font-family attribute.

Generating values automatically

In more recent browsers, you are likely to find websites using RGBA (Red Green Blue Alpha) and HSLA (Hue Saturation Lightness Alpha) colors, rather than the typical hex values that we saw in the previous section.

Not every browser supports these color formats—to get around this, we can declare a hex value first, followed by its RGBA or HSL equivalents. As an example, we might write something similar to the following code in order to turn the text set with the h1 attribute to dark brown:

h1 {
  color: #963529;
  color: rgba(150, 53, 41, 0.5);
}

If we're choosing colors in a graphics package such as Photoshop or GIMP, we might occasionally struggle to get both the values and might need to resort to alternative means. Thankfully, this is not an issue with Less as it allows us to use functions to create new values automatically.

Why will we do this? The answer is simple: all we need to do is provide a color value using one format, such as RGBA. We can then use Less' functions to convert it to a different format—we can then avoid any confusion about ensuring we've provided the right values, as these will be worked out automatically by Less.

Let's take a look at a quick example of how this will work:

.brown-color {
  @rgbaColor: rgba(150, 53, 41, 0.5);

  color: fade(@rgbaColor, 100%);
  color: @rgbaColor;
}

Here, we've used a simple variable to define the base color before using the rgba color function to convert it to its RGBA equivalent value, with the alpha value set to 0.5. If we compile the Less code, it produces the following CSS:

.brown-color {
  color: #963529;
  color: rgba(150, 53, 41, 0.5);
}

The alpha channel in our example is set at 50 percent. This means that we can see 50 percent of whatever is behind the color in the browsers that understand RGBA. The use of functions will really come into their own when creating themes for sites—we could potentially create a whole host of colors from just two to three base colors!

We will explore more about the color functions later in this book, in Chapter 12, Color Processing with Less.

Forgetting about vendor prefixes

The beauty about using CSS3 is that there's no need to always use images, when we can often achieve the same result using pure styling alone. Trouble is, catering to all these new features, such as background gradients, animations, box shadows, and the like, means that we often have to use vendor prefixes or different syntaxes to ensure that the site can be viewed by the widest possible audience.

This can be a real pain but not so much with preprocessors. As you will see later in Chapter 4, Working with Variables, Mixins, and Functions, we can create a mixin or a small block of predefined code that can literally be mixed in our Less style sheet and can be used to create valid CSS. Take, for example, the following block of code, which is used to produce rounded corners:

.roundcorners { 
  -webkit-border-radius: 4px; 
  -moz-border-radius: 4px; 
  -ms-border-radius: 4px; 
  -o-border-radius: 4px; 
  border-radius: 4px; 
}

With Less, there are hundreds of mixins that are available online (more of which we will cover later in the book), which we can use in our code. Instead of having to remember what each style needs in terms of prefixes and syntax, we can just use the following code:

.roundedcorners {
  .border-radius;
}

The preceding code produces exactly the same CSS that was once compiled; Less automatically adds all the vendor prefixes, which is a great time saver.

Creating media queries and animation the simple way

The advent of mobile devices has created a need for responsive websites, which will display content only if the rules meet a specific environmental condition or breakpoint. A good example is determining the size of the screen in use when browsing a responsive website.

This normally means having to write a number of queries for each breakpoint in a design. As an example, we could write the following (simplified) CSS to change the typography for a particular device:

@media only screen and (max-width: 529px) {
  h1 {
    font-size: 0.7em;
  }
}

@media only screen and (max-width: 949px) {
  h1 {
    font-size: 0.9em;
  }
}

@media only screen and (max-width: 1128px) {
  h1 {
    font-size: 1.1em;
  }
}

Even though this is only setting the size for the h1 attribute, it seems like a lot to remember. We can simplify the code using the power of Less:

@smallwidth: ~"only screen and (max-width: 529px)";
@mediumwidth: ~"only screen and (max-width: 949px)";
@largewidth: ~"only screen and (max-width: 1128px)";

h1 {
    @media @smallwidth { font-size: 0.7em; }
    @media @mediumwidth { font-size: 0.9em; }
    @media @largewidth { font-size: 1.1em; }
}

We start by declaring three variables, each containing the media query statements. These are static values and will only change if we decide to add or modify any of the supported breakpoints. It isn't essential to use them in this instance, but it will help make the nesting solution easier to read!

We then call each media query using @media, followed by the variable that contains the breakpoint we wish to test against. The key point here is that while it might look like @media is repeated, we can't base our nesting style on @media as the code will fail to compile. Instead, we need to base it on the h1 selector for the code to compile correctly.

Reusing code across multiple projects

One of the limitations of CSS is that we often find ourselves applying the same values across multiple elements, throughout each site that we build. On a small site, this is less of an inconvenience, but for larger sites, there is a greater risk that we may miss updating a value, which could produce unexpected results. We've seen how you can reduce (or even eliminate, with good planning), the risk using variables—what if we could reuse our code in future projects?

This is not as crazy as it might seem—we may develop a specific drop-shadow style for buttons that we like and want to reuse. The conventional way is to store this in a text file, database, or the likes, and then dig it out each time we need to reuse it. It's a cumbersome way to do it, even if it does work—the need to do this is eliminated if we use a preprocessor.

We can simply store the code in a file, in the form of mixins or reusable blocks of code. If we need to reuse any of them, we simply add the file to our project and use the following command to import the contents:

@import "mixinfile.less";

The beauty of using Less though means that it will only import those mixins that are needed for our project in the main CSS file.

Compressing CSS automatically for faster websites

So far, we've talked about some of the compelling features of Less—a fraction of what it offers—there is a lot more that we will cover throughout the book as well as taking a look at some of the more practical uses of Less.

There is one key thing to writing CSS that we've not mentioned: the ability to compress your style sheets as part of releasing your site into production. Compressing our style sheets removes white space and allows us to concatenate multiple files in one master CSS file.

Why should you do this? The answer is easy: it will make style sheets a fraction of the size of the original, which saves on bandwidth. While this is probably less of an issue for normal Internet connections, it is critical for those using mobile devices with limited bandwidth.

How will you compress your CSS? Sure, we could compress it using an online tool, but this means using an extra tool, which adds to your already busy development. There is no need to do this when using Less—if you compile your code using one of the GUI tools, such as WinLess, or even the command line, you can set it to compress the code at the same time.

This is just a taste of what Less can offer. Before getting up and running the development tools we will need for using Less, let's take a brief look at what CSS4 will offer and how this might affect preprocessor tools such as Less.