Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Bootstrap Site Blueprints Volume II
Bootstrap Site Blueprints Volume II

Bootstrap Site Blueprints Volume II: Maximize the potential of Bootstrap for faster and more responsive web applications

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Bootstrap Site Blueprints Volume II

Chapter 1. Advanced Bootstrap Development Tools

Although Bootstrap is the most popular CSS framework on the block, which polarizes web developers of all skill levels, one of the main complaints against it is that it's too large and hard to use. The primary goal of this book is to give you an advanced set of tools to make building websites with Bootstrap easier and even enjoyable. We'll start out by showing you how to create a development environment and workflow that is easy to set up and reuse in all your Bootstrap projects. From there on, we'll tackle a number of common website designs to get you comfortable with the advanced techniques. Finally, we'll include some JavaScript libraries and really take our Bootstrap projects to the next level. Sit back, fire up your code editor of choice, and get ready to dive into some advanced Bootstrap blueprints.

In this chapter, you'll learn:

  • How to create a development environment with Harp.js
  • How to run a localhost server with Node.js to preview your project
  • How to write templates with EJS and use variables and partials
  • How to set up your theme with Less in the most efficient manner
  • How to compile your project for production

Theming is hard!@

I won't lie. Bootstrap theming can be really challenging. There is a large library of components that take some time to understand, and learning the best ways to customize them also takes time. But what if there was an easier way? I'm happy to say that I've designed a workflow using some modern frontend development tools that make it much easier to work with Bootstrap. The problem with frontend languages such as HTML and CSS is that they lack some core programming features, such as variables and includes. Thanks to tools such as Less for CSS and Harp.js for templating, these missing features are now available for building static websites.

Harp.js – the static web server with built-in preprocessing

The title says it all, and it is taken from the official http://harpjs.com/ website. Harp is an open source project from some of the same people who brought us PhoneGap, and it is my tool of choice for any static website project I work on. Why is Harp so great? Here are just a few reasons:

  • It includes automatic preprocessing of languages such as EJS, Jade, Markdown, CoffeeScript, Less, Sass, and Stylus
  • Harp converts the aforementioned languages into vanilla HTML, CSS, and JavaScript and feeds it to the browser
  • It allows powerful templating through the use of common layouts and partials or includes for PHP people
  • It includes a lightweight web server that compiles your code in the background for quick and easy testing
  • It passes in custom metadata through JSON to save your time
  • It compiles all of your code into production-friendly files that you can deploy on your server.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Creating a development environment

Everything that I outlined earlier basically creates a development environment for your Bootstrap websites. The advantage of using a development environment is that you can use tools such as Harp to make your website development faster and easier. It provides you with a working copy on your local computer, and you can use that copy to develop your projects. When you're done, you can compile it into the production version and deploy it on the Internet. It's a good idea to get into the habit of creating a development environment because it's a better coding practice and makes it easier to maintain your project in the future. This is because the production code is totally separate from the source development files. Running a localhost server for testing also allows you to build new features without having to worry about negatively affecting your live production website.

Installing Node.js

The web server that is built into Harp runs on Node.js. Therefore, you will need to install Node on your computer before you can set up Harp. If you don't have Node already installed, head over to the following link to download the version you need:

http://nodejs.org/download/

Once you've downloaded and installed Node, you'll have to open and use the command line to test the installation. If you're on a Mac, I'd recommend that you use the terminal or an app such as iTerm to access the command line. If you're working on Windows, you can use Cygwin. Once you've opened up your command-line app, type in the following line:

$ node -v

If you have installed Node correctly, the number of the version you have installed should be printed on the terminal. You should see something like this:

$ v0.10.33

Great! Now we can move on to installing Harp.

Installing Harp.js

Actually, setting up Harp.js is really easy. If you have closed your terminal, open it again. Insert this command if you're on a Mac:

$ sudo npm install -g harp

If you're on Windows, use the following command:

$ npm install -g harp

After you execute this command, you should see a bunch of packages being installed in the terminal window. Once everything stops loading, Harp is installed. To verify that it has worked, enter the following in the terminal and hit Enter:

$ harp version

This should give you the version number, which means that Harp was successfully installed.

Since Less preprocessing is included with Harp, we don't need to install anything special to use Less. This is great news, because we don't need to rely on less.js or a standalone compiler app. Once we compile our Harp project and run the web server, any changes to Less files will be picked up automatically. For now, just celebrate, and we'll cover compiling Less in more detail a little later.

Setting up a boilerplate project

For the rest of this chapter, I'm going to teach you how to set up a Bootstrap boilerplate project in Harp. Moving forward, this boilerplate will be the basis for all the projects in the book. One of the great things about Harp is that you can simply copy and paste a project to create a new instance of it on your local machine. There are also some other commands that you can run to generate project scaffolding, and I welcome you to check them out at http://harpjs.com/docs/. However, for this book, we aren't going to take any shortcuts, and I'm going to show you how to manually set up a project. The best practice is to do it the hard way first so that you learn how it works. This will save you a headache down the road if you are troubleshooting a problem. The first thing you should do is navigate to a directory on your computer where you want to store your project. In the directory you created the following files and sub directories. For the time being, just leave the .json and .ejs files blank. We'll fill them in a little later. Take a look at the following image to see how your project directory should look.

Note

Note that there is a project boilerplate available for download or forking from GitHub at https://github.com/cardeo/booterator.

Setting up a boilerplate project

This is the root of our project, and here we'll find everything at a high level:

  • /css: This directory will contain all our custom CSS and the Bootstrap framework CSS files.
  • /fonts: This directory will be for holding any web fonts or icon web fonts. The directory isn't totally necessary, but I always include Font Awesome with all my projects so that I have an icon library to pull from.
  • /img: This directory will hold all the images for the project. For the boilerplate, we won't actually need any images, but we're setting this up for future projects too.
  • /js: This directory will hold any custom libraries and the Bootstrap framework's JavaScript file.
  • /partial: This directory will hold the pieces of code that we want to reuse in our templates, such as our header and footer.
  • _data.json: This is the file in which we will define any metadata that we want to use in our template. An example of this could be the page title for each web page.
  • _harp.json: This is a file for setting global properties, such as the title of the website, which is used on all pages.
  • _layout.ejs: This file is the scaffolding for our page. It includes the <head> and <body> sections of our document. At the very least, you need one layout in every Harp project. It is possible to have multiple layouts if you want to load in JavaScript libraries to only some pages.
  • index.ejs: This file holds the actual code for our boilerplate home page. This is the body or content of the page minus the wrapping template pieces that are held in _layout.ejs.

Note

The Embedded JavaScript (EJS) template language is very similar to HTML and is therefore really easy to grasp. The advantage of using EJS is that it allows the use of elements such as variables.

Setting up the CSS

Now that the root of our project is set up, let's set up the subdirectories. We'll start with the CSS directory by adding the following files. Now would be a good time to download the latest version of Bootstrap from http://getbootstrap.com if you haven't done so already. Again, just leave theme.less blank for now.

Setting up the CSS

Within the components directory, create a Less file and name it _variables.less. Leave this file blank for the time being.

Note

Starting a file with an underscore in Harp will mark it as a template file that should not be a straight copy to the production directory. It is file that should be compiled into another to create a full HTML page or CSS style sheet.

Let's quickly walk through the files in the /css directory:

  • bootstrap.min.css: This is the Bootstrap CSS framework. When you download the Bootstrap package, there are a number of other CSS files. We don't need any of those files; we only need the minified version of the framework.
  • /components: This is a directory for storing the Bootstrap component's Less files. If you are customizing a Bootstrap component, you should create a Less file for it and enter the custom CSS.
  • theme.less: This is the master file for our CSS. All our components should be imported into this file so that upon compilation, it will be a single theme.css file for our project.

Setting up the fonts

Bootstrap comes with Glyphicons out of the box, which is fine. I, however, prefer to use font awesome because their license is more flexible. To add font awesome to your project, head to http://fontawesome.io and download the package. Unzip it into your computer after downloading and copy the contents of the /fonts directory to your project's /fonts directory. Next, go to the /css folder and copy font-awesome.min.css to your project's /css directory. For now, that's all you need to do; we'll hook up everything else a little later. The /fonts directory should now look like this:

Setting up the fonts

Setting up the JavaScript

For our boilerplate, all that we need to do is copy bootstrap.min.js to our /js directory. Like the Bootstrap CSS, there are a few JavaScript files included in the download package. You can ignore the other files as we won't need them.

Setting up the partials

The last directory that we need to set up is our partials. If you come from the PHP world, note that partials are includes. They are little snippets of code that are reused across all or many of your pages, such as your header, footer, and navigation. Partials are one of the best features of Harp because you can update these template pieces in one place when changes occur, instead of updating on every page! For now, create two files in your /partial directory, called _header.ejs and _footer.ejs.

Now that we've finished setting up the basic structure of our project, we can move on to actually filling in some code for our .json and .ejs files.

Setting up _harp.json

I'm going to start with _harp.json before _data.json. This is because the first file deals with the global settings for our project. In this case, we're going to use _harp.json to set up a global variable that will map to the website name for our project. Later on, we'll insert this variable into our layout so that it appears on every page of our website. Enter the following code and save it:

{
  "globals": {
    "siteTitle": "My Bootstrap Boilerplate"
  }
}

What we've done here is set up a global variable named siteTitle and set its value to My Bootstrap Boilerplate. Once we insert this variable into our layout, the title will be shown on every page of our project.

Note

This is only a fraction of what you can do here. Check out http://harpjs.com/docs/development/globals to learn more about globals.

Configuring _data.json

If _harp.json applies to all the pages in our website, _data.json contains page-specific data for our project. In this case, I'm going to set up a variable that can be used to insert the page name for each page of my project:

{
  "index": {
    "pageTitle": "Home"
  }
}

Here's how this data works:

  • The index refers to the name of my ejs template that I want to target. Currently, we have only one, called index.ejs.
  • The pageTitle is a variable I created for the title of each of my pages. We'll need to insert this variable into the layout later on.
  • Finally, I entered a value of Home for my variable.

Again, there is more that you can do with metadata in Harp, but at this point, this is all that we need. To learn more about Harp metadata, visit http://harpjs.com/docs/development/metadata.

Setting up the layout

As I mentioned previously, _layout.ejs is the wrapper file for my index.ejs page template. Layouts can be reused, and pages will always default to using _layout.ejs unless you tell them otherwise. If you want to create a second layout for use on a specific page, you simply have to create a new file called something like _layout-two.ejs. Then, in your _data.json file, you have to add a second line to your template declaration that points to the new layout:

{
  "index": {
    "pageTitle": "Home", 
    "layout": "_layout-two"
  }
}

Note

When you're working with your .json file, file extensions are not required.

Now, that's an example of how to use multiple layouts. For our boilerplate, we'll need only one layout. A layout file can be written in mostly normal HTML, but we need to insert a yield property to tell Harp where to insert the content from the page file (index.ejs). We also need to insert the variables that we defined in _harp.json and _data.json. Open up your _layout.ejs file in the root of the project and insert the following <head> code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><%- pageTitle %> | <%- siteTitle %></title>

  <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
  <link rel="stylesheet" type="text/css" href="css/theme.css">

  <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->
</head>

The preceding code is the standard Bootstrap header with some small changes:

  • Always load the Bootstrap CSS first, as you may want to overwrite something in your theme
  • Include the font awesome CSS file so that you can use the icons in your projects
  • Insert your theme CSS file, which will contain all your custom CSS

Note

Make sure you use the CSS extension here for all your files. Once theme.less is compiled, it will turn into theme.css. Therefore, we need to name it correctly so that it's picked up by the browser.

Inserting the variables

If you look at the <title> tag in <head>, you'll notice a couple of variables. These are the two variables that we set up in _harp.json and _data.json. On compiling, pageTitle and siteTitle will be inserted into the page layout. Depending on the page, the proper pageTitle variable will be inserted.

Now that we have the <head> element of our layout set up, let's enter the code for <body>:

<body>
  <%- partial("partial/_header") %>

  <%- yield %>

  <%- partial("partial/_footer") %>

  <!-- javascript //-->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="js/bootstrap.min.js" type="text/javascript"></script>
</body>
</html>

Now, the <body> code is going to look a little different from what we are used to with Bootstrap and HTML. Let me go through each part of the layout:

  • The header partial will include our header code, which we haven't set up yet.
  • The yield tag is the marker for loading in the contents of our pages. In this case, it will load index.ejs.
  • Like the header, the footer partial will be included wherever the tag is inserted.
  • At the bottom, I've included jQuery and a link to the Bootstrap JavaScript framework that is in our project.

Setting up the header

To set up the header, we need to edit the _header.ejs file that we created earlier in this chapter. Head to the /partial directory and open up _header.ejs. Then paste the following in the Bootstrap navbar code:

<nav class="navbar navbar-default" role="navigation">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar1">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
     <a href="index.html" class="navbar-brand"><%- siteTitle %></a>
    </div>

    <div class="collapse navbar-collapse" id="navbar1">
      <ul class="nav navbar-nav">
       <li><a href="index.html">Home</a></li>
      </ul>
    </div>
  </div>
</nav>

The code for the header is pretty straightforward, except for one thing; it's your standard Bootstrap navbar. One more thing that is different is that I've used the siteTitle global variable again so that siteTitle will automatically be inserted into the navbar brand for each page upon compilation. This is a simple example of how you can reuse variables in your templates.

Setting up the footer

Next, open up the _footer.ejs file, which is in the same /partial directory. Here, we'll just want to insert some super simple footer code that can be used as a placeholder. Notice how I'm wrapping my footer in a container-fluid class. It's a good idea to componentize the pieces of your theme so that they are easily interchangeable and don't rely on markup in other components or partials:

<div class="container-fluid">
  <div class="row">
    <div class="col-lg-12">
      &copy; 2015 Matt Lambert
    </div>
  </div>
</div>

As you can see, it is super simple! The last template or HTML/EJS work that we need to do is set up the body of our page, which lives inside of index.ejs. For our boilerplate, let's create a super simple piece of page content:

<div class="container-fluid">
  <div class="row">
    <div class="col-lg-12">
      <h1>Bootstrap Boilerplate</h1>
      <p>This is a Bootstrap starter template built with Harp, Less, CSS, EJS, and HTML</p>
      <p>Made in Vancouver by <a href="http://twitter.com/cardeo">@cardeo</a></p>
   </div>
  </div>
</div>

This chunk of code should be self-explanatory. I've purposely kept it simple so that you can easily see where the lines between page templates and partials are. Now that the base of our project is set up, let's compile and preview it!

Compiling for the first time

Now that our initial project is set up, it's time to compile it and test it out to make sure that everything works. When we compile our project for the first time, Harp creates a directory in the root of our project, called /www. Within this directory, it will dump all the compiled HTML, CSS, and JavaScript files. When you are ready to publish your project, simply upload the contents of this directory to your server. See how simple and clean it is? Your development and production files live in the same project directory but are totally separate.

Note

You should never manually edit any of the files in your /www directory. If you do, on the next compilation, any changes you make will be overwritten.

The compilation of your project is done from the command line or terminal app. If you have closed it, open it again and navigate to your project directory. Once you get there, run the following command:

$ harp compile

If all goes well, a new line should appear in the terminal. If there is an error, Harp will give you an error message with a clue to the problem. Let's assume that all has gone well and everything has worked fine. Go to your project directory and look for the /www directory. If it's there, it means that the compile worked fine.

Running the local server

The next thing you'll want to do is actually test your project in a browser. To do this, we can use Harp's built-in web server to test the website locally. This is a great feature because you can test drive your project locally without having to upload it to the Internet. To fire up the server, enter the following command in the terminal from your project directory:

$ harp server --port 9000

This will deploy your project locally on port 9000. Open up a web browser and go to http://localhost:9000 to view the website.

Your page should look like this:

Running the local server

Now that you have the server running, you can take advantage of one of Harp's other awesome features. Every time you make a change to a template file, CSS file, and so on, you don't have to recompile your project. You can simply save the file and refresh the browser, and you'll see the updated version. This will save you so much time! One thing to remember, however, is to make sure you compile when you're done so that the changes are applied to the /www directory.

I encourage you to memorize the preceding commands, but if you want something easier to remember, you can use $ harp server www to run the local server. The only problem with this command, however, is that I've found it to be a bit buggy. It will start the server but updates to templates in the background won't always be picked up. A more reliable method is to manually declare which port to use when you fire up the server. Now that our project is all set up and running, it's time to set up our Less configuration to theme our project.

Configuring Less

A great advantage of using Harp is that it has a built-in Less compiler. When you run the $ harp compile command, it compiles both your .ejs templates and your .less files into regular HTML and CSS. This is much easier than using something like less.js, which you would have to remove from production. When you're compiling your project for the first time, ensure that you include some code inside your theme.less file. Otherwise, theme.css will not be written.

Defining your Less variables

Head back to the css/components directory that you created earlier and open up the _variables.less file. Within this file, we'll configure what I call global CSS variables. Moreover, within this file, we'll define only those variables that apply across our entire website. Component-specific variables have no place in this file. I know that some developers like to have one big file for variables, but I prefer to keep the component-specific ones out in their own Less files. We will see more on that later, when we dive into custom components. For now, let's start pasting the following code in _variables.less.

Colors

Let's start by inserting some color variables that can be used throughout all our Bootstrap projects:

@black: #000;
@dark-grey: #333;
@grey: #ccc;
@light-grey: #ebebeb;
@off-white: #f5f5f5;
@white: #ffffff;
@blue1: #3498db;
@blue2: #2980b9;
@red1: #e74c3c;
@red2: #c0392b;
@yellow1: #f1c40f;
@yellow2: #f39c12;
@green1: #2ecc71;
@green2: #27ae60;
@orange1: #e67e22;
@orange2: #d35400;
@aqua1: #1abc9c;
@aqua2: #16a085;
@purple1: #9b59b6;
@purple2: #8e44ad;
@navy1: #34495e;
@navy2: #2c3e50;

As you'll see, I like to define a fairly large color palette. But this doesn't mean that all my projects will use all of these colors. However, like a good typography, it's a good idea over time to develop a library of colors that work well together. We can then easily include them in all our projects so that we have colors that work well together right at our fingertips. When you are diving deep into theming, this is really valuable because you don't have to go and look for a new color palette with every new theme. You already have a collection of colors that you can pull from, which will speed up your theming process.

Backgrounds

Lets add the background variables:

@primary-background: @white;
@secondary-background: @off-white;
@third-background: @light-grey;
@fourth-background: @grey;
@inverse-background: @dark-grey;

Tip

The preceding code is my boilerplate for backgrounds. Note how these colors use a variable name for their value and not a hexadecimal value. The reason that this is done is to speed up theming. Instead of having to change a color in two places, we only have to change it in one, and then it inherits throughout our other variables. Here are a few more key points about backgrounds.

The variable naming convention here is similar to that of Bootstrap, for consistency. This also makes it easier to remember a variable name, such as primary, as against something like white-background.

At the very least, you should have a primary, a secondary, and an inverse background. I like to include a couple more, but feel free to scale this back a bit if it makes it easier for you.

Text

As with our backgrounds, we are following the Bootstrap naming conventions for our text colors:

@primary-text: @dark-grey;
@light-text: @light-grey;
@loud-text: @black;
@inverse-text: @white;
@heading-text: @dark-grey;

Consistency is the key as it makes it easier to remember variable names. It is critical when you're dealing with a large framework that you make things as easy as possible to remember. Again, make sure you use color variables for the values here and not actual hexadecimal numbers.

Links

Defining the link colors is pretty straightforward:

@primary-link-color: @blue1;
@primary-link-color-hover: @blue2;

One thing that I'll point out here is that this is the first example where you'll see why you should have at least two versions of every color that you use in your palette. Things such as hover states usually require a base color and a darker or lighter version of the same color to indicate a change in hovering. You may want to expand this section to include a second or even third-link color variation.

Borders

The border variable is the first place where you'll see some values that aren't only color-based:

@border-color: @light-grey;
@border-size: 1px;
@border-type: solid;
@border-focus: @grey;
@secondary-border-color: @blue1;

In this case, you should always set your size to 1px. The reason for this is that you can use a Less operation like the following to increase the size of your border. Starting from 1px makes your operations simple and easy to follow for other developers who may be maintaining or editing your code:

.good-class {
  border-size: (@border-size + 1);
}

.bad-class {
  border-size: 2px;
}

Tip

Never use pixel values in any of your custom CSS! You would want to use variables so that you can make any units relative and, therefore, controlled by a variable. This will allow you to quickly spin up a new theme by only editing the variable's Less file.

Typography

Next we need to setup the global settings for our typography variables. We'll set our body and heading font stacks, a base font size and line height.

@body-copy: "Helvetica Neue", helvetica, arial, verdana, sans-serif;
@heading-copy: "Helvetica Neue", helvetica, arial, verdana, sans-serif;
@base-font-size: 14px;
@font-size: 1em;
@base-line-height: 1.5;

When I set up typography for a theme, I like to follow a few simple rules:

  • Make sure you define at least a body and a heading copy variable.
  • Set the base font size as a pixel value.
  • Set the actual font size to 1em and use this variable throughout your custom CSS. In this way, you will be using a relative value that is easier with operations. This is exactly the same as the preceding border example.
  • I personally prefer to reset Bootstrap's line-height to 1.5 for easier math.

Layout

The only layout variables that you should be setting in your globals are margin and padding:

@margin: 1em;
@padding: 1em;

Both should be set to 1em for easy relative operations. This follows the same unit of measurement patterns set with borders and typography.

Mixins

The other element that I recommend including in your global Less file is mixins. In my opinion, there are only two of them (and maybe only one) that you definitely need to include to speed up your Bootstrap theming.

Border radius

The border radius is by far the most important as it is used a ton through Bootstrap components:

.round-corners (@radius: 2px) {
-moz-border-radius: @radius;
-ms-border-radius: @radius;
border-radius: @radius;
}

Make sure you set this up and use it for everything. If you are thorough, you can change the border radius of all elements in one place. An example of this would look like the following:

.btn {
  /* fill in the rest of the styles here */
  .round-corners;
}

Now, if I change my @radius value to a different pixel amount, it will inherit down to my button corners. Do this for all your Bootstrap components!

Animations and transitions

Another property that I use heavily in my themes is the animations or transitions property:

.transition (@transition: background .1s linear) {
-moz-transition: @transition;
-webkit-transition: @transition;
transition: background @transition;
}

I find that a little transition, when added, can add a lot to a UI. Instead of defining this from the ground up on every component, use this simple mixin. It will speed up your theming time and also ensure that transitions are consistent across your entire theme. That's just good design and coding. Here's an example that shows you how to apply the round corners and transition mixins to a button:

.btn {
  /* fill in the rest of the styles here */
  .round-corners;
  .transition;
}

This completes your _variables.less file. Save the file and close it. Next, we'll cover the setup of the master theme file for our project.

Setting up your theme

Now that we've set up our variables file, we need to set up the master theme that we'll import it into. The master theme file, or theme.less, is the primary file that we will link in the <head> section of our pages. I've organized the theme using the Scalable and Modular CSS (SMACSS) system. Using a modular approach while coding the CSS will make the job easier and the code more maintainable over time.

SMACSS overview

The scalable and modular CSS system was created by Jonathan Snook, who is currently a product manager at Shopify. It divides your style sheet into five sections in order to make it easier to categorize your CSS. Let's review each SMACSS category to see how it applies to our Bootstrap theme structure.

Base rules

A base rule applies to any element that is an element selector, descendent selector, child selector, or pseudo-class. It doesn't apply to CSS classes or IDs. These are basically all your core HTML tags.

Layout rules

The layout section is dedicated to any custom classes that you've written for the layout of your project. This could be something simple, such as a header, or something more complex, such as a widget. If you're following best practices, your layout should only use classes. However, if you have used some IDs, you should include them here as well.

Module rules

This is the big one for Bootstrap, because this is where you should import all your component Less files. Later on, I'll explain how you should break down each Bootstrap component into its own Less file and then import it into the master theme. The code for this will look a little something like the following:

@import "components/_badges.less";
@import "components/_typography.less";
@import "components/_tables.less";

State rules

These styles refer to anything that applies to a state change, such as form validation or alert bars.

Theme rules

This part of your style sheet is optional. You may cover it in the preceding sections. However, if you find yourself needing a section for styles specific to your theme, this is where you should insert them.

Now that I've explained how we'll organize our master theme, let's actually start putting it together. The first thing we need to do is import the _variables.less file that we created. We want this to be the first thing that we load into the theme, so we place the following line of code at the top:

@import "components/_variables";

Note

With the variables file in Harp, you shouldn't include the file extension. The reason behind this is that multiple preprocessor types are supported and variables is a keyword.

Setting up the base

The next section that we want to set up in our theme is the base. Insert the following boilerplate CSS. We want to keep this really basic so that we have a starting point for our future projects:

body {
  background: @primary-background;
  font-family: @body-copy;
  font-size: @base-font-size;
  line-height: @base-line-height;
  color: @primary-text; 
}

ul,
ol {
}

li {
}

a, a:link, a:visited {
}

a:hover {
}

p {
}

hr {
}

I'm not even going to fill in any of the tags at this point, as they will be defined in the actual project. The only tag I will fill in is <body>. Let's review the properties that we have added to the body tag at the top of the preceding section of code:

  • We'll set our background to the @primary-background variable. The @primary-background variable should be set to the color you want for the background of your project.
  • We set the font-family property to our @body-copy variable.
  • Set the font-size property to the @base-font-size variable. Remember that this is the one that has the pixel value, and it should be a value of this type on the body tag. In any future use of the font-size property, you should use the @font-size variable.
  • The line-height is set using the @base-line-height variable.
  • Finally, we'll set the font color to our @primary-text variable.

As I mentioned earlier, we'll leave the rest of this section blank as it will be filled in to match the actual project that we will be designing in the future.

Setting up the layout

Since this is a boilerplate project, we don't really have a layout. We can fall back on the Bootstrap's grid and we don't need anything custom. Therefore, just leave this section blank for now, but you might want to insert a comment to show where the layout code should be inserted for future projects:

/*
02. LAYOUT
Styles specific to your layout or website
*/

Setting up the modules

This section should be a list of @import keywords that load into our Less component files. As I mentioned earlier, you should break down any custom Bootstrap component CSS into its own Less file and save it in the /components directory. This is the way to keep your CSS neat and tidy in the development version of your theme. On compile, all of these Less files will be combined into a single CSS file called theme.css. However, for development purposes, it makes a ton of sense to break down the CSS for easier maintenance and writing.

As you create a project, you may not need to overwrite code in every Bootstrap component. Personally, I think it's good practice to customize everything, but it's not always practical to do this. The following is a list of potential Less component files that you can make with Bootstrap:

  • badges
  • breadcrumbs
  • buttons
  • button groups
  • button dropdowns
  • carousel
  • code
  • collapse
  • dropdown
  • forms
  • icons
  • input groups
  • images
  • helpers
  • jumbotron
  • labels
  • The list group
  • The media object
  • modal
  • navs
  • navbar
  • pager
  • The page header
  • pagination
  • panels
  • pills
  • popover
  • progress bars
  • scrollspy
  • tables
  • tabs
  • thumbnails
  • tooltip
  • typography
  • well

When you're creating a component Less file, first save it at css/components, and then use the @import keyword to import it into theme.less. You need a different @import statement for each file to load it in:

@import "components/_badges.less";
@import "components/_typography.less";
@import "components/_tables.less";

Setting up the states

With Bootstrap, the States section works much like modules, but I like to divide the following two components into the states section:

@import "components/_alerts.less";
@import "components/_form-validation.less";

These two make sense from a Bootstrap component standpoint. If you are using a different JavaScript library to perform your form validation, you should include the corresponding styles here. This should also apply for any component that has a state change.

Setting up the theme

The final section is the theme, and it is totally optional. One thing that would be theme-specific is your color palette. I break my color palette into another Less file and import it under the modules section.

You may be wondering what goes into this colors.less file, since we have defined our colors in the _variables.less file. In the variables file, we only assign hexadecimal numbers to variables. In the colors.less file, I assign these variable names to actual CSS classes so that we can use them in our layouts. In this way, we stay more modular because we can assign a color class to a widget instead of putting the color in the widget's CSS layout code. I usually define a text and background color class for each color in my palette:

.red1 {
  color: @red1;
}

.red1-bg {
  background: @red1;
}

.red2 {
  color: @red2;
}

.red2-bg {
  background: @red2;
}

Now, those class names are way easier to remember than hexadecimal numbers, and this allows you to apply them to a widget, as follows:

<div class="custom-box red1-bg">this is a custom box with a red background</div>

Using this method, I can leave out any color styles in my custom-box class and only worry about layout styles. I can then apply the color using a CSS class, which is much more modular and reusable.

Finishing up theme.less

Now that we've finished the last section of theme.less, our style sheet is ready to roll. Go back to the terminal and compile your project again. Once that's done, go to www/css and you should see theme.css. Our boilerplate CSS development environment is ready to roll for an actual project.

Summary

In this chapter, you learned how to—and why it's important to—build a development environment with Harp.js. You also learned how to write templates in EJS using variables and partials. Lastly, you got to know how to set up your theme with Less and compile your project for production.

In the next chapter, we'll begin our first project, where we'll build a full-fledged restaurant website. Eager to get started? Flip those pages and dive right in!

Left arrow icon Right arrow icon

Key benefits

  • Build Bootstrap projects quickly and easily with Harp.js, Node, and Less
  • Learn how to extend Bootstrap with the use of open source JavaScript and icon web font libraries
  • Get acquainted with building complex social networking, wiki, and dashboard projects with Bootstrap

Description

Bootstrap is the most popular open source project on GitHub today. With a little bit of know-how, this massively popular CSS framework can leveraged for any type of complex web application or website. Bootstrap Site Blueprints Volume II will teach you to build these types of projects in an easy-to-understand fashion. The key to any complex Bootstrap project is a strong development foundation for your project. The book will first teach you how to build a Bootstrap development environment using Harp.js, Node, and Less. In the next chapters, we’ll build on this foundation by creating restaurant and mobile-first aggregator projects. Once you’re warmed up, we’ll move on to more complex projects such as a wiki, a new magazine, a dashboard, and finally a social networking website. Whether you are brand new to Bootstrap or a seasoned expert, this book will provide you with the skills you need to successfully create a number of popular web applications and websites.

Who is this book for?

Bootstrap Site Blueprints Volume II is geared for developers of all experience levels. It is written in a concise, easy-to-understand way. Each project follows a step-by-step process that anyone can understand. Some experience with Bootstrap beforehand would definitely be an asset but is not required.

What you will learn

  • Customize and extend existing Bootstrap JavaScript components
  • Combine the Google Material Design look and feel with Bootstrap
  • Use flexbox and other cutting-edge CSS3 techniques in Bootstrap
  • Implement and customize open source JavaScript chart libraries in Bootstrap
  • Optimize and implement an optimal user experience for all your projects
  • Implement the Disqus commenting platform into your projects
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 06, 2016
Length: 328 pages
Edition : 1st
Language : English
ISBN-13 : 9781785281099
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Jan 06, 2016
Length: 328 pages
Edition : 1st
Language : English
ISBN-13 : 9781785281099
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 116.97
Bootstrap Site Blueprints
€37.99
Bootstrap 4 By Example
€36.99
Bootstrap Site Blueprints Volume II
€41.99
Total 116.97 Stars icon

Table of Contents

8 Chapters
1. Advanced Bootstrap Development Tools Chevron down icon Chevron up icon
2. Building a Restaurant Website Chevron down icon Chevron up icon
3. Mobile First Bootstrap Chevron down icon Chevron up icon
4. Bootstrap Wiki Chevron down icon Chevron up icon
5. Bootstrap News Magazine Chevron down icon Chevron up icon
6. Bootstrap Dashboard Chevron down icon Chevron up icon
7. Bootstrap Social Network Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(2 Ratings)
5 star 50%
4 star 50%
3 star 0%
2 star 0%
1 star 0%
Lisa Nov 04, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is great for developers who have some knowledge of HTML, CSS, Bootstrap and want to get to the next level. It is very easy to follow and references other great developer tools.
Amazon Verified review Amazon
Svein Soermo Apr 12, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
High quality projects and very good explanations.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela