Hour 23. Using Less and Sass with Bootstrap


What You’ll Learn in This Hour:

Image What a CSS preprocessor is

Image Some basic features of Less

Image How to use Less to update your Bootstrap website

Image Some basic features of Sass

Image How to use Sass to update your Bootstrap website


Bootstrap ships with plain CSS, but it uses both Less and Sass CSS preprocessors. You can use them to adjust how your Bootstrap website looks. In this hour you learn the rudiments of these preprocessors and how to use them with Bootstrap.

What Is a CSS Preprocessor?

Many people often think that CSS doesn’t need preprocessing, and for small sites that is probably the case. But preprocessors make doing large or extensive changes across websites much easier.

A CSS preprocessor is a language that extends CSS and adds traditional programming features such as variables, loops, if-statements, and so on. Then the code is compiled into standard CSS for use in web browsers. CSS preprocessors add a number of benefits you can’t get with plain vanilla CSS:

Image Don’t Repeat Yourself (DRY)—CSS forces you to write many styles over and over and over. CSS preprocessors let you define variables and snippets of reusable code so you’re not typing the same thing repetitively.

Image Cleaner CSS—With a preprocessor, you can do things like nest styles and use variables to store information so the styles make more sense.

Image Faster updates—If you have a large site with a large CSS file, it can take a long time to find every instance of a style. But if you have a color defined as a variable, you can change that variable in one place and know that every button, text block, or background using that color is changed.

Image Cross-browser support is built in—Although browsers are getting better and better at using the official CSS properties, there are still a lot of prefixed styles and styles that require different syntax across browsers. Rather than looking it up every time and for every style that might need to be prefixed, preprocessors will add the correct CSS automatically.

Image Scripting—Vanilla CSS is very straightforward and simple. If you need a style to be applied only in certain circumstances, you will need to apply it with JavaScript. But preprocessors include many scripting features to let you vary the styles right in the CSS.

Image Share CSS across sites—You can store your CSS blocks as shareable library files to use in other pages or sites. You also can get snippets or libraries from other people on the Web so you don’t have to build complex styles from scratch.

Using Less

Less is the preprocessor that Bootstrap comes with by default. By understanding some of the basic features of Less, you can improve how your Bootstrap sites work.

Less Features

Less has a lot of features that make it preferable to using plain CSS, including

Image Variables

Image Mixins

Image Operations

Image Functions

A variable in Less is a name/value pair defined at the beginning of a Less file. The variable or name starts with the @ sign and is separated from the value by a colon (:). You then use the variable anywhere you want that value to appear in your CSS. Listing 23.1 shows a simple color variable and how it’s used in the Less CSS file.

LISTING 23.1 Simple Less Variable


@yellow: #F0E433;

p.pull-right {
  color: @yellow;
}


When you compile the Less, it will generate CSS replacing the variable @yellow with the color code #F0E433.

Mixins are a way of including properties from one rule set into another rule set. For example, say you had a class called .center-block that centered block elements. You could include that class in any other style property that you wanted centered as a mixin. Listing 23.2 shows a simple Less mixin.

LISTING 23.2 Simple Less Mixin


.centered-block {
  margin-right: auto;
  margin-left: auto;
}

h1 {
  width: 80%;
  .centered-block;
}


This will make all <h1> tags both 80% wide and centered.

Mixins also allow you to create default values but then change them in specific instances. For example, you might want to have most of your borders be 3px wide but want to be able to change the border width when needed. Listing 23.3 shows how to use a mixin with a default value and how to change that value.

LISTING 23.3 Parametric Mixins


.green-bordered(@borderwidth: 3px) {
  border: solid green @borderwidth;
}

p.pull-right {
  .green-bordered();
}

p.wide-border {
  .green-bordered(10px);
}


This sets the p.pull-right style to the default border width, while the p.wide-border style has a border width of 10px.

Operations allow you to adjust any number, color, or variable using math functions. This is straightforward when you’re talking about adding or subtracting values from a number, like a width. But you also can add or subtract colors using color math.

For example, @width: 10px + 5; results in the output of 15px whenever the @width variable is used. Listing 23.4 shows how you might darken a color by a specific amount using operators and color math.

LISTING 23.4 Changing a Color with Operators


@yellow: #F0E433;
@other-yellow: @yellow - #666;

p.pull-right {
  color: @yellow;
  text-shadow: 2px 2px @other-yellow;
}


This creates a second color that is related to the first color mathematically. It is the base yellow color (#f0e433) minus #555 or #9b8f00.

Less has many built-in functions you can use to adjust your CSS. Functions change CSS from a simple text-based language to a programmable tool. There are functions to modify strings of text, list functions to get the length of a list or specific elements in a list, math functions for converting numbers, type functions to evaluate values, color functions for working with color definitions and channels, as well as functions to help you change and blend the colors you have.

In Bootstrap you see a lot of the color operation functions to create monochromatic color palettes. Listing 23.5 shows the grayscale color scheme created using just the color black (#000) and the lighten and darken functions.

LISTING 23.5 Create a Color Palette with Less Functions


@gray-base: #000;
@gray-darker: lighten(@gray-base, 13.5%);
@gray-dark: lighten(@gray-base, 20%);
@gray: lighten(@gray-base, 33.5%);
@gray-light: lighten(@gray-base, 46.7%);
@gray-lighter: lighten(@gray-base, 93.5%);

.black {
  color: @gray-base; // @gray-base
}
.darkest {
  color: @gray-darker; // @gray-darker
}
.dark {
  color: @gray-dark; // @gray-dark
}
.gray {
  color: @gray; // @gray
}
.light {
  color: @gray-light; // @gray-light
}
.lightest {
  color: @gray-lighter; // @gray-lighter
}


As you can see, these functions are much easier to understand what’s going to happen than using the color math operations mentioned earlier. If you want to use a different color for @gray-base, you can—and this will generate a monochromatic color scheme for you.

There is much more to Less than can be covered in one hour. If you’re interested in learning more, you should start with the Less home page at http://lesscss.org/.

Using Less with Bootstrap

It’s easy to use Less with Bootstrap because Bootstrap is built with Less by default. You can use the source Less files, rather than the compiled CSS, to create your own custom designs. Or you can use the variables and mixins that are already created.

If you are going to work with the Less files, you will need to have a setup for compiling the CSS. Bootstrap recommends using Grunt (http://gruntjs.com/).

After you have Bootstrap and Grunt installed, you can edit the files in the source code directories—less/, js/, and fonts/—to reflect your website styles, scripts, and fonts. Use the grunt dist command to regenerate your distribution files.


Caution: Run Grunt Commands in the less/ Directory

If you run the Grunt commands from within the distribution directory, all your files will be removed because there are no Less files to compile there. However, if you do this, don’t panic. Just change to the less/ directory and rerun the Grunt command: grunt dist. This will re-create your entire distribution directory.


Using Sass

Sass (http://sass-lang.com/) is another CSS preprocessor that works with Ruby or inside applications such as Compass (http://compass.kkbox.com/). Many web designers are switching from Less to Sass because Sass offers more features than Less does. It also solves some problems that Less can have, such as when using the @ symbol for variable names.

But to use Sass with Bootstrap, you have to use a different port of Bootstrap that is adjusted to use Sass. You’ll learn more about that in the section “Using Sass with Bootstrap.”

Sass Features

Sass has many of the same features as Less, including

Image Variables

Image Mixins

Image Operators

Image Nesting

Image Logic and loops

Variables work the same way in Sass as they do in Less. You replace long strings or commonly used code blocks with short words or phrases. The only difference is that Sass uses the $ rather than the @ sign to define variables. This has the advantage of not being confused with CSS @ declarations such as @media and @import. Plus, many other programming languages use the dollar sign as a variable identifier. Listing 23.1 showed a simple Less variable; Listing 23.6 shows you the same variable in Sass.

LISTING 23.6 Simple Sass Variable


$yellow: #F0E433;

p.pull-right {
  color: $yellow;
}


Mixins also work in a similar way to Less, but you define them with the @mixin directive. You can pass variables to your mixins as well. Then, you just include the mixin in the style(s) you need it in using the @include directive. Listing 23.7 shows how to use a simple Sass mixin.

LISTING 23.7 Simple Sass Mixin for Rounded Corners


@mixin border-radius($radius) {
  -webkit-border-radius: $radius;
  -moz-border-radius: $radius;
  -ms-border-radius: $radius;
  border-radius: $radius;
}

.box { @include border-radius(10px); }


Mixins are often used to deal with browser prefixes, and you can find lots of examples of useful Sass mixins online. A number of mixins are built right into Bootstrap. One of my favorites is the @mixin size() mixin. This mixin takes two parameters: width and height. You can then set your Bootstrap elements to specific sizes with just one line of code. Listing 23.8 shows how.

LISTING 23.8 Using the size() Mixin


.myImage {
  @include size (400px, 300px)
}


Like in Less, you can use operators to do math from within your Sass CSS files. You can perform many other operations, including these:

Image Number operations—These are the standard math operations you’re familiar with such as width: 100px * 2px.

Image Color operations—You also can add, subtract, multiply, and divide colors just like in Less. These operations work on the red, green, and blue channels in turn.

Image String operations—Use the + operator to concatenate strings together.

Image Boolean operations—You can use the and, or, and not operators for Boolean values.

Nesting lets you include the rules for one property inside another. This makes the CSS appear more like it does in the HTML itself. Listing 23.9 shows a simple nested style and how it compiles into CSS.

LISTING 23.9 A Nested Style and the Resulting Compiled CSS


// Sass code
#main p {
  color: #000000;
  width: 98%;

  .highlight {
     background-color: #f1b161;
  }
}

// Output CSS
#main p {
  color: #000000;
  width: 98%;
}
main p .highlight {
  background-color: #f1b161;
}


You can extend styles so that they have the same styles as the previous style, but with some extra. For example, you might have a standard paragraph style with a font family and background color set. Say you want your <aside> tags to look the same as your paragraphs but with a border around them as well. Listing 23.10 shows how easily you can do this in Sass using the @extend directive.

LISTING 23.10 Using the @extend Directive


.standard {
  font-family: "Source Sans Pro";
  background-color: #e6b29a;
}
aside {
  @extend .standard();
  border: solid #efefef 1px;
}

// compiled CSS
.standard, aside {
  font-family: "Source Sans Pro";
  background-color: #e6b29a;
}
aside {
  border: solid #efefef 1px;
}


Although Less has some logic statements (when) and a little bit of looping, Sass has these features fully developed. It has if/then/else statements, for loops, and each loops. These work exactly how they work in other programming languages.

There is a lot more to Sass than can be covered in this book. If you are interested in learning more, I recommend starting with the Sass documentation online at http://sass-lang.com/documentation/file.SASS_REFERENCE.html.

Using Sass with Bootstrap

Bootstrap is built on Less, but there is an official Sass port on GitHub: https://github.com/twbs/bootstrap-sass. You can install Bootstrap with Sass support manually, but it’s easiest to use a tool like CodeKit (https://incident57.com/codekit/), Compass.app (http://compass.kkbox.com/), or Prepros (https://prepros.io/) that will automatically watch your files and compile them when necessary. These tools make it easy to use Sass and Bootstrap without having to worry about command-line tools or installing Ruby. You just download the program of your choice, install it, and set it to check the directories where you are storing your SCSS files.

After you have Sass installed and a compiler set up, you can edit your SCSS or Sass files exactly as you want to make your site as unique as you like.

Summary

This hour you learned about how to customize your Bootstrap installations using the Less and Sass preprocessors. You learned some of the basic features of both Less and Sass and learned how to get started editing Less and Sass files. You also learned how to compile them to make your Bootstrap sites look amazing.

Workshop

The workshop contains quiz questions to help you process what you’ve learned in this hour. Try to answer all the questions before you read the answers.

Q&A

Q. Where can I go to learn more about Less and Sass?

A. The first place you should start with both languages is their home pages: http://lesscss.org/ for Less and http://sass-lang.com/ for Sass. If you prefer learning from video courses, Lynda.com (http://www.lynda.com/) has several courses on both Less and Sass.

Q. If I customize the Bootstrap variables, what will happen when a new version of Bootstrap comes out?

A. It depends on how you update your files. If you edited the bootstrap CSS files directly (or the corresponding Less or Sass files), then those files might be overwritten when you load a new version. Your best solution is to create all your changes in a separate file and then load the file using include files with Less or Sass. Listings 23.11 and 23.12 show how you can include files using Less and Sass, respectively.

LISTING 23.11 Including Files with Less


// import the file my-bootstrap-styles.less
@import "my-bootstrap-styles.less"


If the file to import is in a different directory, include that inside the quotes.

LISTING 23.12 Including Files with Sass


// import the file _my-bootstrap-styles.scss
@import "my-bootstrap-styles"


The main difference between the two files is that the Sass file does not need to include the file extension (scss) or the underscore at the beginning of the filename.

Quiz

1. Why would you want to use a CSS preprocessor?

a. To stay current with design trends

b. To improve the flexibility of your website

c. To manage large or extensive changes on a website

d. To keep your CSS looking nice

2. What is a good reason to not use a CSS preprocessor?

a. When you have a small site with little or no CSS.

b. When you don’t want to compile CSS.

c. When you don’t know the languages.

d. You should always use a CSS preprocessor.

3. What does DRY mean in the context of CSS preprocessors?

a. Don’t Reuse sYmbols

b. Don’t Repeat Yourself

c. Do Repeat Yourself

d. Nothing

4. True or False: CSS preprocessors let you use if/then/else statements.

5. How do you define a Less variable?

a. The at sign (@)

b. The caret symbol (^)

c. The dollar sign ($)

d. The hash symbol (#)

6. True or False: Less mixins do not accept parameters.

7. Which of the following is a Less function?

a. light

b. lighter

c. lighten

d. lightest

8. How do you define a Sass variable?

a. The at sign (@)

b. The caret symbol (^)

c. The dollar sign ($)

d. The hash symbol (#)

9. True or False: The following code is valid in Sass:

font-family: sans- + "serif";

10. Which preprocessor allows for for loops: Less or Sass?

a. Both

b. Less

c. Sass

d. Neither

Quiz Answers

1. c. To manage large or extensive changes on a website

2. a. When you have a small site with little or no CSS

3. b. Don’t Repeat Yourself

4. True

5. a. The at sign (@)

6. False

7. c. lighten

8. c. The dollar sign ($)

9. True

10. c. Sass

Exercises

1. Install Grunt on your machine and set it up to watch a Bootstrap Less directory. Then make some changes to the Less files, and compile them using the Grunt command grunt dist. After you have compiled your CSS, upload it to your web server to view it live.

2. Install Compass on your machine and use it to install Sass. Then create a new Bootstrap with Sass folder, and build a new website using what you’ve learned in previous hours.

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

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