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
Bootstrap Site Blueprints

Bootstrap Site Blueprints: Without Bootstrap your web designs may not be reaching their full potential. This book will change that through a series of hands-on projects covering everything from custom icon fonts to JavaScript plugins.

eBook
€19.99 €28.99
Paperback
€37.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

Chapter 1. Getting Started with Bootstrap

Bootstrap's popularity as a frontend web development framework is easy to understand. It provides a palette of user-friendly, cross-browser tested solutions for most standard UI conventions. Its ready-made, community-tested combination of HTML markup, CSS styles, and JavaScript behaviors greatly speeds up the task of developing a frontend web interface, and it yields a pleasing result out of the gate. With the fundamental elements quickly in place, we can customize the design on top of a solid foundation.

But not all that is popular, efficient, and effective is good. Too often, a handy tool can generate and reinforce bad habits; not so with Bootstrap, at least not necessarily so. Those who have watched it from the beginning know that its first release and early updates have occasionally favored pragmatic efficiency over best practices. The fact is that some best practices, right from semantic markup to mobile-first design to performance-optimized assets, require extra time and effort to implement.

Quantity and quality


If handled well, I will suggest that Bootstrap is a boon for the web development community in terms of quality as well as efficiency. Since developers are attracted to the web development framework, they become part of a coding community that draws them increasingly into current best practices. From the start, Bootstrap has encouraged implementation of tried, tested, and future-friendly CSS solutions, from Nicholas Galagher's CSS normalize to CSS3's displacement of image-heavy design elements. It has also supported (if not always modeled) HTML5 semantic markup.

Improving with age

With the release of v2.0, Bootstrap helped take responsive design into the mainstream, ensuring that its interface elements could travel well across devices, from desktops to tablets to handhelds.

Now, with its v3.0 release, Bootstrap has stepped up its game again by providing the following features:

  • The responsive grid is now mobile-first friendly

  • Icons now utilize web fonts and are thus mobile- and retina-friendly

  • With the drop of support for IE7, markup and CSS conventions are now leaner and more efficient

The power of leaner CSS

In addition, there is the power of Leaner CSS (LESS) to consider. When we move beyond merely applying classes to markup and take the next step to dig in and customize Bootstrap's LESS files, we gain tremendous power and efficiency. Starting with a solid basis using Bootstrap's default styles, we can move on to innovate and customize to our heart's content.

In other words, Bootstrap is a powerful resource. I intend to help you leverage it in exciting and serious ways, working with efficiency, adhering to best practices, and producing beautiful, user-friendly interfaces.

Downloading Bootstrap


There are many ways to download Bootstrap, but not all ways of downloading Bootstrap are equal. For what follows, we must be sure to get the LESS files as these files give us the power to customize and innovate upon Bootstrap's underlying style rules. For this exercise, we'll go straight to the source, that is, GetBootstrap.com.

Once there, the large Download source button is your friend. At least as of Version 3.0.2, this is the second large button on the homepage of GetBootstrap.com.

In case something should change, you can always follow the GitHub project link, and once at the GitHub repository, click on the Download ZIP button.

The files you'll have

Once you've downloaded the Bootstrap source files, you should see a file structure that is similar to the following screenshot:

Admittedly, that's a lot of files, and we don't need them all. On the plus side, we have everything we want from Bootstrap.

While the exact contents of the repository will change over time, the main contents will remain relatively consistent. Most notably, in the less folder, you will find all the important LESS files, which are key to every project in this book. Another benefit is that the js folder contains Bootstrap's individual JavaScript plugins so that these may be selectively included as needed.

On the other hand, if you want Bootstrap's default precompiled CSS or JavaScript files (such as bootstrap.css or bootstrap.min.js), those are still available within the dist folder. As a bonus, you'll find the example HTML templates in the examples folder. In fact, we'll use one of these examples to set up our first project template folder.

Preparing a project template folder


Let's create a folder with the essential files we'll need to launch a project. We'll use the excellent HTML5 Boilerplate (H5BP) for our starting point, folding Bootstrap's files in their appropriate places.

Getting H5BP

Navigate to h5bp.com in your browser, a short link that will redirect you to H5BP's main documentation page. You may download the H5BP files directly from this page or from the linked GitHub project by clicking on the SOURCE CODE tab available at h5bp.com.

Extract the ZIP file and rename the folder to Project Template 1.

Inside this folder, you'll find the file and folder structure as shown in the following screenshot:

Note

If your file system does not show hidden files, you will not see the .htaccess file. In my case, I have used my FTP browser to navigate to my local folder to make the .htaccess file visible.

Deleting unnecessary Boilerplate files

Delete the following folders and files, which are specific only to H5BP:

  • The css folder because we'll soon create our own CSS files using LESS

  • CHANGELOG.md

  • CONTRIBUTING.md

  • The doc folder and its contents

Evaluating the Boilerplate .htaccess file

If you have not read about the H5BP's .htaccess file before, you should take a look at the H5BP documentation, which is featured prominently at http://h5bp.com. In addition, the file itself is very well commented. Open it in your editor and read through it. Depending on your hosting setup and the needs of your site, you may or may not need all or a part of what this file does. Part of the purpose of what's in this file is to maximum site performance. Take it seriously, consult wise advice, and decide accordingly. In my case, my hosting provider handles these things, and so I don't need the .htaccess file.

Updating required Boilerplate files

The following files provide standard information about your project. They may be updated and used, if desired, or you may leave them out. It's up to you.

  • humans.txt: This file assigns appropriate credits to you, H5BP, Bootstrap, and any other contributors.

  • LICENSE.md: Prior to the H5BP license, add your own desired licensing information for the website you'll build with this license. After H5BP's license, add the licensing information for Bootstrap and other libraries that play a significant role in your end product.

  • README.md: Update this file to provide a basic orientation to the entire project.

Updating the favicon and touch icons

Remember to replace the Boilerplate's default icon images with your desired images for your project. These include the following icon images:

  • apple-touch-icon-precomposed.png

    • For best results across all mobile devices, including high-pixel-density screens, this should be 144px square (or 152px as in the Boilerplate version).

  • favicon.ico

    • A 32px square icon image.

Note

Previous versions of the Boilerplate once included as many as six sizes of touch icons. Recently, this strategy was re-evaluated. Because the large icon will be used by all relevant devices, and the performance hit is very very small, it has been decided to reduce development overhead and have only one touch icon. For the discussion, see https://github.com/h5bp/html5-boilerplate/issues/1367#ref-pullrequest-18787780.

Pulling in the Bootstrap files


We are ready to pull Bootstrap's files into our Project Template 1 folder and file structure. We'll move down through the big Bootstrap repository, selecting out only the parts we need. To speed up this process, I highly recommend having your Bootstrap 3 files open in one file browser window and your project template files open in another to facilitate comparing, dragging, and dropping.

Fonts

From the main Bootstrap folder, copy the fonts folder, and paste it into the main directory of your Project Template 1 folder. This contains the important Glyphicon fonts that come with Bootstrap. (If you've not used font icons before, you're in for a treat.)

For good measures, I'm going to suggest that you add a cross-domain-friendly .htaccess file to this folder. Why? As more hosting services provide Content Delivery Network (CDN) for your site's static assets, you may discover, as I have, that some browsers refuse to recognize your web fonts without this access file. (Note that the H5BP .htaccess file contains lines to take care of this. The step we are taking now is aimed at ensuring that we do not run into problems even if the H5BP .htaccess file is not in the root directory of the site.)

Create a new file in your code editor, and add the following lines:

<FilesMatch "\.(ttf|otf|eot|woff)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

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.

Save the newly created file directly inside the fonts folder naming it .htaccess. (Note that if you're working locally, your OS may make the file invisible. If you have trouble getting your OS to make hidden files visible, you can often view it again by using your FTP client, setting its preferences to view hidden files, and using it to navigate to this folder.)

Once in place, the .htaccess file travels with your fonts folder, ensuring that your web fonts work in all browsers across whichever hosting and CDN services your websites may use.

JavaScript

Now let's try to bring in Bootstrap's JavaScript. Thanks to the HTML5 Boilerplate, we already have a JavaScript folder (named js) in place. Inside this, you'll find four files, two of them inside a subfolder named vendor, as shown in the following screenshot:

Bootstrap's plugins make use of jQuery, and the Boilerplate has it ready for us. Alongside jQuery, you'll see the Modernizr script. If you're unfamiliar with Modernizr, it includes an HTML5 shiv, which enables HTML5 sectioning elements in Internet Explorer 8. We're supporting IE8 in these projects, and so we need this here. In addition, Modernizr enables us to test for specific browser capabilities easily, such as CSS 3D transforms (to read more, see http://modernizr.com/docs/). We'll use Modernizr's feature-detection powers in the last chapter of the book.

Now, we need to add Bootstrap's plugins to the mix. First, let's bring them over as a group of individual plugins. Inside the main js folder of your Project Template 1 folder, create a subfolder named bootstrap. Now copy into this the files you'll find in Bootstrap's js folder. The following are the Bootstrap's plugins, each as an individual file:

By copying and pasting these plugins into your new js/bootstrap folder, when you're ready to optimize your site for performance, you can select just the plugins you need, thereby eliminating the others and reducing file size.

Meanwhile, it may be helpful to have all of Bootstrap's plugins available during the development phase. That way, if you need to add an accordion, a tooltip, or a carousel, you can do it at your whim. Let's do this for ourselves now.

The H5BP method of doing this is to paste the code for all plugins into the provided plugins.js template file. This is a best practice when we're finished and ready to optimize the site because fewer HTTP requests means faster site loading times. (Loading one file of, say, 80 KB is more efficient than loading four files of 20 KB each.)

While developing, it's fairly convenient to use this same structure. It simply requires that we copy and paste the code for our required plugins into the plugins.js file. Let's find Bootstrap's big file of plugins and do this here.

Note

You may prefer to work otherwise during the development stage, adding links to individual plugins to your markup during development, and then rolling the plugins into one minified file at the end. If you prefer that method, you can ignore this set of instructions and replace them with your own steps.

From Bootstrap's main folder, navigate to the dist folder to find the distribution files. Here, in the js folder, are bootstrap.js and bootstrap.min.js, containing all of Bootstrap's plugins rolled into one fat file. We will not be editing the plugins in these exercises, so let's use the minified version.

Once you've found it, perform the following steps:

  1. Open bootstrap.min.js in your editor.

  2. Copy the code, including the comment at the top. (Select all, then copy.)

  3. Now, open plugins.js from your new project files.

  4. Paste Bootstrap's plugin code inside the file, below the // Place any jQuery/helper plugins in here. comment. So, you'll now see something like the following:

    // Place any jQuery/helper plugins in here.
    
    /**
    * bootstrap.js v3.0.0 by @fat and @mdo
    * Copyright 2013 Twitter Inc.
    * http://www.apache.org/licenses/LICENSE-2.0
    */
    if(!jQuery)throw new Error("Bootstrap requires jQuery");+function(a){"use strict";
    ...

    And of course the rest of the lengthy block of code will follow.

  5. Save and exit.

You now have Bootstrap's plugins loaded and ready!

Note

By keeping the comments from the top of Bootstrap's plugins, as well as from any other plugins we may include down the line, we are giving credit where credit is due and including essential licensing information. We're also making it easier for ourselves to search and sort through our plugins later. For instance, while optimizing the following projects for production, you'll want to substitute minified versions of only the specific Bootstrap plugins you'll be using in the project. Keeping these comments in place will help greatly at that point.

Holding off on the CSS

In the later projects, we are going to create a custom version of the Bootstrap CSS using LESS. We'll be doing this early in the next chapter, so hold on.

Bringing the LESS files over

Let's bring over all the important Bootstrap LESS files. Copy the bootstrap/less folder to the main directory of your Project Template 1 folder.

Taking inventory


The main folder of your Project Template 1 folder should now look like the following screenshot:

Your fonts folder, with the new .htaccess file within it, should contain the following files:

Note

I've used my FTP client to view these files, and set it to show hidden files. You may not be able to see your .htaccess file without taking similar steps.

The img folder should be empty, as was the H5BP folder from which it came.

The js folder should contain the following subfolders and files:

Because of its modular approach, Bootstrap's less folder contains a long list of files. We'll double-check these as we prepare to compile them in the forthcoming sections.

First, let's set up an HTML file.

Setting up the HTML template file


From your new project folder, open index.html in your editor. This sample markup file came with H5BP and contains several best practices and recommendations within it. We'll build on this basis and integrate it with our Bootstrap workflow. First, let's take a moment to note what's in it.

Scanning down through the file, you'll notice several interesting features. These are clearly explained in the H5BP documentation. You may easily get there from http://h5bp.com, but let me briefly run through a few of the features here. You'll see them in the following order:

  • The HTML5 doctype:

    <!DOCTYPE html>
  • Conditional comments for Internet Explorer, which enable developers to compose fixes for older IE browsers using appropriate nested selectors:

    <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
    <!--[if IE 7]><html class="no-js lt-ie9 lt-ie8"><![endif]-->
    <!--[if IE 8]><html class="no-js lt-ie9"><![endif]-->
    <!--[if gt IE 8]><!--><html class="no-js"><!--<![endif]-->
  • The html tag also has a class of no-js. If a browser's JavaScript is enabled, this class will be removed by the Modernizr script (referenced in the preceding part of this chapter) and replaced with the class js. If it is not removed, it signals that JavaScript is not enabled, and we may craft CSS rules for such cases using nested selectors.

  • You'll see meta tags for the following things:

    • Specifying the character set as follows:

      <meta charset="utf-8">
    • Instructing an IE browser to use the most updated version of its rendering engine, or to use Google's Chrome Frame if it is installed as follows:

      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    • The description tag for providing a description of the site is as follows:

      <meta name="description" content="">
    • A mobile-friendly viewport meta tag will be as follows:

      <meta name="viewport" content="width=device-width">
  • In place of links to a favicon or touch icon, you'll find a comment recommending that we simply place the icons in the site's root directory, where they will automatically be found by the users' browsers and devices.

  • You'll see two stylesheet links—one to normalize.css and another to main.css—as follows:

    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/main.css">
  • Then, you will see a script tag loading the Modernizr script. This needs to be loaded here in order for the HTML5 shiv it contains to equip IE8 so that it recognizes the HTML5 sectioning elements.

    <script src="js/vendor/modernizr-2.6.2.min.js"></script>
  • Then there is an IE conditional comment, with a message recommending the users of older IE browsers to upgrade to a more modern browser.

    <!--[if lt IE 7]>
      <p class="chromeframe">You are using an <strong>outdated</strong> browser. ...
    <![endif]-->
  • A single paragraph of content text.

  • A link to Google's hosted version of jQuery, followed by a link to a local fallback copy of jQuery:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
  • Links to plugins.js and main.js, which are intended to hold the code for JavaScript plugins (in plugins.js) and your custom code (in main.js):

    <script src="js/plugins.js"></script>
    <script src="js/main.js"></script>
  • The Google Analytics script:

    <script>
      var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
      (function(d,t){var g=d.createElement(t),
        s=d.getElementsByTagName(t)[0];
      g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
      s.parentNode.insertBefore(g,s)}(document,'script'));
    </script>

If you wish to know more about the reason and purpose for any of these elements, I would encourage you to take some time to read through the H5BP HTML documentation (see https://github.com/h5bp/html5-boilerplate/blob/v4.3.0/doc/html.md), where these lines are clearly explained with references.

For our purposes, we will perform the following operations on the elements of this template:

  1. We'll give our site a title. We'll update the legacy IE conditional comment for users of old browsers.

  2. We'll compile Bootstrap's CSS from the LESS files. We'll add some basic page content.

  3. We'll integrate Bootstrap's JavaScript plugins and ensure that the responsive navbar works as it should.

Once we've done the these things, we'll have everything in place to begin building our designs.

Giving your site a title


Take a moment to update index.html by giving it a title that fits this project. You can call your portfolio whatever you'd like to. I'll call mine as Bootstrappin' Portfolio. For the sake of precision, I'll use the HTML entity ' for the apostrophe, as shown in the following line of code:

<title>Bootstrappin' Portfolio</title>

Adjusting the outdated browser message

The file carries a message for users of ancient browsers. You'll find this right around line 20. It reads as follows:

You are using an outdated browser. Please upgrade your browser or activate Google Chrome Frame to improve your experience.

Note that it includes links to http://browsehappy.com, which features recommended browser upgrades, and to the Google Chrome Frame, a free plugin to retrofit Internet Explorer with modern browser capabilities. (Note that the Google Chrome Frame reference may go away after Google stops supporting it in January 2014.)

At the time of writing this book, this message came wrapped in a conditional comment that targets only Internet Explorer browsers older than IE7 (thus, IE6, IE5, and so on). No one else will see this message unless, of course, they view the source code.

Meanwhile, the world is pressing on. Many organizations are upgrading browsers, and many designers are dropping or reducing support for IE7. Typically, the goal is to ensure that IE7 users can navigate through the site and gain access to its information, though they will not have the full experience.

The reason for this is pretty pragmatic. Fully supporting IE7 requires writing a number of workarounds, both in CSS and in JavaScript, at the cost of more code, more bandwidth, more time, and more money.

Thus, Bootstrap 3 has dropped support for IE7. When we're done developing, we should test to ensure nothing restricts IE7 users from reading and navigating through our site. However, they won't see its full beauty.

So, let's update the message to include IE7 users. We need to change the opening tag of the conditional comment by adding an e for = , so that it reads the following:

<!--[if lte IE 7]>

Note that it now says lte where originally it was only lt.

A few notes seem in order.

Note

For IE7 and older browsers, you might consider providing basic styles in a legacy stylesheet to ensure these users can utilize your site.

If you have a large base of users who rely on IE7 and who are unlikely to be able to upgrade, you probably need to consider reverting back to Bootstrap 2.2.3, which supports IE7.

Note that if you would like to see what this message looks like, and perhaps customize its style, you can view it in any browser by temporarily deleting or commenting out the IE comment at the beginning (<!--[if lte IE 7]>) and at the end (<![endif]-->).

Setting up major structural elements

We're almost ready for page content. Right now, there's only a paragraph. Let's go ahead and get a bit more content rolling. Specifically, we'll create the following:

  • A banner space with our logo and navigation

  • A main content space for page content

  • A footer area for copyright information and social links

We'll set this up using current HTML5 best practices with the support of major Accessible Rich Internet Applications (ARIA) role attributes (with roles such as banner, navigation, main, and contentinfo). If you've been following HTML5 but not closely in the past few months, note the recently added element, <main role="main"></main>, whose purpose is to provide a sectioning element dedicated to the main content of a page or section. For more information, see this sitepoint article at http://www.sitepoint.com/html5-main-element/.

So, consider the following comment and paragraph:

<!-- Add your site or application content here -->
<p>Hello world! This is HTML5 Boilerplate.</p>

And replace the preceding code with the following:

<header role="banner">
  <nav role="navigation">
  </nav>
</header>

<main role="main">
  <h1>Main Heading</h1>
  <p>Content specific to this page goes here.</p>
</main>

<footer role="contentinfo">
  <p><small>Copyright &copy; Company Name</small></p>
</footer>

This gives us some basic page structure and content. Let's keep rolling.

Providing a navbar markup


You'll remember that we have not brought over the precompiled CSS files from Bootstrap, nor have we yet compiled CSS from our LESS files. We'll do the latter shortly. But first, let's put at least one Bootstrap-specific element in place, that is, the navbar.

Initially, we want only Bootstrap's basic navbar (we'll add other details later). I've used the markup taken from Bootstrap's documentation and adjusted it in the following ways:

  • I've added the class navbar-static-top since we want the navbar to be positioned at the very top, and yet scroll with the page

  • I've linked the brand link to index.html

  • I've changed the parent div tags to semantic HTML5 nav tags

The preceding adjustments lead to the following result, nested with our header element:

<header role="banner">
  <nav role="navigation" class="navbar navbar-static-top navbar-default">
    <div class="container">
      <div class="navbar-header">
        <a class="navbar-brand" href="index.html">Project name</a>
      </div>
      <ul class="nav navbar-nav">
        <li class="active"><a href="index.html">Home</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
      </ul>
    </div>
  </nav>
</header>

Save your results, and open or refresh index.html in your browser. You'll note that we don't have much yet, as shown in the following screenshot:

We have content. Now, we desperately need our stylesheet to come to the rescue. Let's compile and link up Bootstrap's default styles.

Compiling and linking default Bootstrap CSS


We could have just brought over Bootstrap's default bootstrap.css file, but let's use this opportunity to take a trial run at compiling the LESS files. This will ensure we've got the fundamentals ready for doing more serious work to come.

Compiling Bootstrap CSS

If you've worked with LESS before, this will be a familiar territory. If you have not worked with LESS before, I'll help you along. However, I highly recommend that you stop and refer to the documentation at http://lesscss.org. Additionally, you may want to find a good basic LESS tutorial and work through it. As you'll soon see, working with LESS is powerful and fun, and the time spent learning will reward well.

For this first step, we won't be writing any LESS files, only compiling.

Navigate to less/bootstrap.less and open it in your editor. You'll see that this file imports all the other files from the less folder. When compiled, this file generates the complete bootstrap.css stylesheet. This is what we want for our first step.

If you've not compiled LESS files before, you'll need to download and install one of the following compilers:

Once your chosen LESS compiler is downloaded, installed, and ready for action, the following are your steps to be performed:

  1. Create a new folder named css in the main directory at the same level as the fonts, img, js, and less folders.

  2. Use one of the following two methods to add your project's main folder (the parent folder of css, fonts, img, less, and so on) to your compiler:

    • Drag-and-drop the folder into the application window

    • Alternatively, navigate to the application's File | New Project menu to add the parent folder

  3. You should see that the application loads the LESS files (and perhaps other files) into its window. Search or scan for the less/bootstrap.less file.

  4. Right-click on bootstrap.less. Select Set output path (or your application's similar option). Navigate to the css folder you created earlier. The file should automatically be named bootstrap.css. Click on Select.

  5. With the output path set, now click on Compile.

  6. Check to see that bootstrap.css was created in the css folder.

    Note

    If you run into problems, check your compiler's log to ensure it was successful, then double-check your output path. In addition, you may run into a situation where your chosen compiler runs into an error because it has not been updated to stay in sync with the development of LESS. I have recently found this with another free compiler. If your compiler refuses to compile the default Bootstrap LESS files, it's an indication that the compiler needs updating.

  7. Once the file is in place in the css folder, we only need to coordinate our file's name with the stylesheet link in our index.html file.

  8. In index.html, remove the stylesheet link to css/normalize.css, as normalize is included in Bootstrap (normalize.less is the first file imported by bootstrap.less).

  9. The remaining stylesheet link looks for the css/main.css file. Because we'll be customizing Bootstrap to generate our own custom stylesheet, let's leave this link as it is. In the forthcoming steps, we'll use main.css for the custom styles we generate.

  10. For now, let's cheat by making a copy of bootstrap.css. In the css folder, create a copy of boostrap.css. Name the copy as main.css (in the future steps, we'll overwrite this file with our customizations) as shown in the following screenshot:

  11. Refresh your browser. You should now see Bootstrap 3's default navigation styles, and you'll see some typographic enhancements as shown in the following screenshot. This is Bootstrap CSS at work. Congratulations!

We now have the default Bootstrap styles in place. Now, let's complete our navbar by making it responsive. As a bonus, this will test to ensure that Bootstrap's JavaScript plugins are working as they should.

Completing the responsive navbar

To complete our navbar to take advantage of Bootstrap's responsive navbar solution, we need to add two new elements, with appropriate classes and data attributes. You'll find this documented under Bootstrap's Components page, under the Navbar tab at http://getbootstrap.com/components/#navbar.

We'll begin by adding the necessary additional markup as follows:

  1. Search for <div class="navbar-header">. Inside this element, we'll add the navbar-toggle button, which will be used to slide the responsive navbar open and closed. The following is what you'll need (and I will include the navbar-header as the parent element):

    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="index.html">Project name</a>
    </div>

    A few notes about the preceding code are as follows:

    • The button includes a class of navbar-toggle for CSS styles.

    • The data attributes are used by Bootstrap's collapse JavaScript plugin to indicate its desired behavior and its desired target, namely an element with the navbar-collapse class. This element is coming in the next step.

    • The spans of the icon-bar class are used by the CSS to create the small horizontal bars in the toggle button.

  2. Now to wrap the navigation items within a collapsing div, wrap <ul class="nav navbar-nav"> with a div with the appropriate Bootstrap classes as follows:

    <div class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li class="active"><a href="index.html">Home</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
      </ul>
    </div><!--/.nav-collapse -->

In the preceding two steps, I've divided the resulting code into two halves and all within <div class="container">. To double-check your work, see the full code in the sample code for this chapter.

Note

The tag structure, class names, or data attributes may change with future versions of Bootstrap. If yours does not work as it should, be sure to check Bootstrap's own documentation. As a fallback option, you can start with the starting files provided with the sample code for this book.

Now save the file and refresh your browser. Using a modern browser (such as IE9 or a recent version of Firefox, Google Chrome, or Safari), click on and drag the edge of the browser window to make the window narrower than 980px.

If all works as it should, you should see a collapsed version of the navbar, as shown in the following screenshot, with the site name or logo and a toggle button.

This is a good sign! Now click on the toggle button, and it should slide open, as shown in the following screenshot:

Success! Congratulations!

Troubleshooting

If things are running smoothly at this point, it means that you've successfully compiled Bootstrap's CSS from LESS, and you've also successfully included Bootstrap's JavaScript plugins.

If things are not running smoothly, you should double-check the following things:

  • Is your markup properly structured? Any unclosed, incomplete, or malformed tags, classes, and so on present?

  • Did you successfully compile Bootstrap's LESS to CSS? And did the resulting CSS file wind up in the correct folder under the proper name?

  • Is the CSS link in the head of index.html updated as it should be?

  • Have you successfully included Bootstrap's JavaScript plugins?

You might find it helpful to do the following:

  1. Work back through the preceding steps, double-checking things along the way.

  2. Validate your HTML to ensure it's well formed.

  3. Compare the completed version of the exercise files with your own.

  4. Refer to the Bootstrap documentation for new updates to the relevant tag structures and attributes.

  5. Place your code in a snippet at http://jsfiddle.net/ or http://www.codepen.com/, and share it with the good folks at http://stackoverflow.com/ for help.

When we have so many moving parts to work with, things do happen. And these are some of our best survival methods!

Now, assuming things are working, let's move on to take care of one more potential problem. We intend to support Internet Explorer 8 in our designs. To do this, we need to help this older browser out a little.

Adding support for Internet Explorer 8

To support Internet Explorer 8, we need to add a bit of JavaScript that equips the browser to respond to media queries. This is the respond.js polyfill by Scott Jehl.

Bootstrap's own documentation recommends this step for IE8 compatibility. You'll find it referenced briefly in the Bootstrap 3 documentation at http://getbootstrap.com/getting-started/#browsers.

You'll also find respond.js linked in the example HTML templates found in the bootstrap-master download under the examples folder, which is found in the docs folder. There you'll see respond.js linked in the head of the document within an IE conditional comment that limits its use to IE browsers lower than IE9. The HTML5 shiv is also included as follows:

<!--[if lt IE 9]>
  <script src="../../assets/js/html5shiv.js"></script>
  <script src="../../assets/js/respond.min.js"></script>
<![endif]-->

Because we have already included the HTML5 shiv with Modernizr, we can leave that out here. In addition, Andy Clarke has recommended an improved conditional comment that excludes IE mobile browsers to ensure that we do not unnecessarily feed the script to Windows mobile devices that don't need it. See his repository, 320andup, at https://github.com/malarkey/320andup/.

Clarke's recommended code works as follows:

<!--[if (lt IE 9) & (!IEMobile)]>
...
<![endif]-->

Armed with these starting points, we're ready to implement it in our site template files as follows:

  1. Navigate to https://github.com/scottjehl/Respond (you may also search respond.js and find the GitHub link). If you'd like, take a few minutes to scroll down the page and read the documentation to learn more about how it works.

  2. Now to get the file and download the ZIP repository.

  3. Extract the directory, and find the minified version of the file named as respond.min.js.

  4. Copy the file to your project files in the js/vendor directory, right alongside the scripts for jQuery and Modernizr.

  5. Then, add the following lines of code to load the respond.js file, which is wrapped in the targeted IE conditional comment. We'll do this is in the head of index.html, directly beneath the line loading Modernizr.

    <!-- Modernizr -->
    <script src="js/vendor/modernizr-2.6.2.min.js"></script>
    <!-- Respond.js for IE 8 or less only -->
    <!--[if (lt IE 9) & (!IEMobile)]>
      <script src="js/vendor/respond.min.js"></script>
    <![endif]-->
  6. That's it! We've successfully provided IE8 with what it needs so that it responds, as it should, to our mobile-first responsive websites.

    Note

    If you want to test this and do not have IE8 available, you might use an online service such as Browsershots that is available at http://browsershots.org (free) or BrowserStack that is available at http://www.browserstack.com (premium with free trial).

Our site template is almost complete. Let's pause to take stock before moving on.

Summary


If you've made it this far, you have everything you need ready to do some serious work. Taking stock of our progress, we have the following:

  • A solid HTML5 markup structure with many current best practices baked in

  • A standard Bootstrap stylesheet linked up

  • JavaScript linked up and working

  • A responsive navbar

  • Perhaps the most important, we have our LESS compiler ready and working

    Note

    This may be a good point to save a copy of these files so that they're ready for other future projects.

Now it's time to have some fun. In the next chapter, we'll take Bootstrap for a spin, creating a beautiful portfolio site.

Left arrow icon Right arrow icon
Download code icon Download Code
Estimated delivery fee Deliver to Cyprus

Premium delivery 7 - 10 business days

€32.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 21, 2014
Length: 304 pages
Edition :
Language : English
ISBN-13 : 9781782164524
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 Cyprus

Premium delivery 7 - 10 business days

€32.95
(Includes tracking information)

Product Details

Publication date : Feb 21, 2014
Length: 304 pages
Edition :
Language : English
ISBN-13 : 9781782164524
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 74.98
Bootstrap Site Blueprints
€37.99
Learning Bootstrap
€36.99
Total 74.98 Stars icon

Table of Contents

6 Chapters
Getting Started with Bootstrap Chevron down icon Chevron up icon
Bootstrappin' Your Portfolio Chevron down icon Chevron up icon
Bootstrappin' a WordPress Theme Chevron down icon Chevron up icon
Bootstrappin' Business Chevron down icon Chevron up icon
Bootstrappin' E-commerce Chevron down icon Chevron up icon
Bootstrappin' a One-page Marketing Website Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(10 Ratings)
5 star 50%
4 star 30%
3 star 10%
2 star 10%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Chris Malan Apr 18, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book would be best suited for someone who knows a bit about Bootstrap. What it does is take one from a blank page to a fully fledged site using Less, instead of css. Of course, Less is ulitmately turned into css. This is just what I wanted. One thing I can add, which I did not find in the book, is download Crunch to turn Less into css. It works really well.
Amazon Verified review Amazon
John Williams Feb 24, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As a very experienced developer coming from mainly a backend career, I am increasingly being dragged into frontend development, especially with the onset of AngularJS. This book was exactly what I was looking for, not pitched too low and not pitched too high. Covers a few good site examples and plenty of direction for additional resources. A really good book to get those with some knowledge of CSS going in the right direction with Bootstrap and responsive design. I personally prefer electronic books these days, I tend to have my IDE open in half the screen and the book open in the other half, this makes it much easier to keep track of what is going on in the book and transfer it to the IDE, plus it saves getting a programmers neck strain! The book works well in electronic format.
Amazon Verified review Amazon
SuJo May 05, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Bootstrap Site BlueprintsI've been a huge fan of Bootstrap for awhile now, there are a few issues that I had while learning but it was pretty painless to get going and figure new things out as I went along. The documentation is well received via the website for bootstrap but I felt it lacked more robust examples, sure the simple things are there. The robust examples in this book are well written and easy to follow along, I enjoyed the WordPress Theme section, it's widely used and something that every web developer needs to work with at some point in time. This book not only guides you along your path of learning, the examples incorporate various bootstrap elements, and using them when they are needed. This book isn't throwing out an html page with an example of a navbar but a full fledge example of a navbar with full content.Excellent Book and well worth the cost!Publisher Site: [...]
Amazon Verified review Amazon
Ian Doremus Aug 14, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I just finished reading Bootstrap Site Blueprints, Design mobile-first responsive websites with Bootstrap 3 by David Cochran. I would recommend this book to anyone who is serious about learning to use the latest Bootstrap framework.The book is written for the beginner to intermediate front-end developer who is comfortable working with HTML/CSS but wants to take things to the next level. The book would also make a good reference for a more experienced developer.What really impressed me was how Cochran introduces plugins, frameworks, and workflows outside the scope of Bootstrap in order to make life easier for the developer. For example, Bootstrap 3 now comes bundled with LESS files (Leaner CSS). The author spends a chapter bringing the reader up to speed on the principles of LESS and how to best implement it into production.The reader is also introduced to HTML5 Boilerplate, Font Awesome, Respond.js, Masonry, ScrollSpy, and the Roots starter theme for Wordpress. These are each introduced to save the developer time by not having to reinvent something from scratch. Rather then complicate the project Cochran uses these plugins to simplify.The book chapters walk one through building a Bootstrap portfolio theme, Creating a Bootstrap business page, a Bootstrap E-commerce page, a single page Bootstrap site and a bonus chapter on converting a Bootstrap theme into a Wordpress template.The appendix covers optimizing a site for best download speeds, best practices for responsive images and adding touch control to a custom photo carousel. The sample code is very well organized, each chapter has a start and a finish file to make sure the reader understands the code.In conclusion, I have read many books on coding and building websites. Some books look like they will be good but don’t live up to the promise either because of bad code examples that don’t work or grammar that is difficult to follow. David Cochran’s background in academics is evident in reading this book. It is truly fun to read. I felt like I was reading a novel and couldn’t wait to find out what is at the end of the chapter. All his example code works as expected and the table of contents and index are organized very well. Yes I would recommend this book to anyone who has even the slightest interest in learning to use Bootstrap.
Amazon Verified review Amazon
Adam Horvath May 03, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is definitely worth reading. I was afraid of buying it without any review, but I got lucky... Today I've completed it.I have years of experience in web development on backend and database side but 've never used bootstrap or similar framework and responsive mobile-first development is a new world for me.Who is this book for?It's a well-constructed, well-written book. The authors guide you through the topic with suitable examples: one page website, e-commerce product page, business site.The chapters introduce new materials in a balanced way, so after finishing the book I felt I had a practical toolset to build some stuff for profit immediately.Summary: The book easy to follow. This step-by-step format is simple enough for begginers with some basic prior html and css experience.Who is this book not for?If you have built some site with bootstrap and have some week of full time bootstrap experience, probably you will find many well-known stuff. This book is rather for begginers.If you wanna build some professional development workflow with grunt and other tools this book is not for you. And you can't find many advanced topics about extending bootstrap. But after reading the table of content it should be clear.
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