Bootstrap 4 Cookbook

5 (6 reviews total)
By Ajdin Imsirovic
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Installing Bootstrap 4 and Comparing Its Versions

About this book

Bootstrap, one of the most popular front-end frameworks, is perfectly built to design elegant, powerful, and responsive interfaces for professional-level web pages. It supports responsive design by dynamically adjusting your web page layout.

Bootstrap 4 is a major update with many impressive changes that greatly enhance the end results produced by Bootstrap. This cookbook is a collection of great recipes that show you how to use all the latest features of Bootstrap to build compelling UIs.

This book is using the most up-to-date version of Bootstrap 4 in all its chapters. First off, you will be shown how you can leverage the latest core features of Bootstrap 4 to create stunning web pages and responsive media. You will gradually move on to extending Bootstrap 4 with the help of plugins to build highly customized and powerful UIs.

By the end of this book, you will know how to leverage, extend, and integrate bootstrap to achieve optimal results for your web projects.

Publication date:
June 2017
Publisher
Packt
Pages
338
ISBN
9781785889295

 

Chapter 1. Installing Bootstrap 4 and Comparing Its Versions

In this chapter, we will cover:

  • Installing Bootstrap 4 to c9 IDE using npm
  • Installing Bootstrap 4 to c9 IDE via git
  • Installing Bootstrap 4 Jekyll-powered docs
  • Customizing the styles of Bootstrap 4 docs
  • Making custom Grunt tasks in Bootstrap 4
  • Comparing Bootstrap 4 versions with Bower
  • Installing Bootstrap 4 to c9 IDE with Bower
 

Introduction


In this chapter, you will learn how to install Bootstrap 4 via the command line on c9.io. The reason for using Cloud9 IDE in this recipe book is that since it is a web-based IDE, it requires you to have only an internet connection and a web browser to run the IDE, which is available at https://c9.io.

Once you access c9.io via your web browser, you have at your fingertips a fully functional Ubuntu virtual machine. The nice thing about this setup is, if you are, for example, running Windows on your computer, you can avoid many of the setup headaches this would usually entail, such as downloading and installing Ruby and Node. Using a web-based IDE is also great if there is a need to work with multiple computers, or if collaboration is important.

Finally, because of its ease of use and a plethora of features, using Cloud9 IDE will make it easier for the less advanced readers to follow along in some of the more complex recipes.

Note

If you decide to use Windows after all, the recipes in this chapter will include notes that are Windows-specific to make it possible to still follow along. In case there are no notes that relate to how things work in Windows, it is implied that the commands work in Windows as well.

In this chapter, besides learning about how to install Bootstrap 4 via the command line, we will also examine the way it utilizes Grunt for commonly performed tasks, Sass to modularize our CSS, and Jekyll to implement a serverless copy of the official Bootstrap docs.

However, all this comes at a cost. In order to use all that Bootstrap 4 has to offer, we need to be familiar with all of these technologies. For more advanced users, this should not be a problem. Still, an ambitious goal of this book is to be useful for as wide an audience as possible, including less advanced users, while at the same time to still prove valuable to those with more experience, as a quick reference to the brand new version of Bootstrap.

Therefore, in this chapter, we will cover the recipes that deal with this advanced setup and explain in simple terms the workings of Grunt, Sass, and Jekyll.

Note

Note that the official Bootstrap website (getbootstrap.com) runs on GitHub's Jekyll platform.

 

Installing Bootstrap 4 to Cloud9 IDE using npm


This recipe will cover the required steps for installation of Bootstrap 4 via npm on Cloud9 IDE. In order to begin working on this recipe, it is assumed that you have already registered a c9.io account.

Getting ready

To begin, log in to your c9.io account, which will open your Cloud9 IDE dashboard:

Click on Create a new workspace, and a new page will appear with only a few things to fill in. You only need to add the Workspace name and Description, as you like. You can leave the Clone from Git or Mercurial URL empty, as well as leave the default HTML template selected. Finally, click on Create workspace to spin up a new container.

Once ready, you will be greeted with the following tree structure of your folders (displayed in the left sidebar):

The largest window (to the right from the sidebar) will have the README.md file open, but you can open any other file in that area as well. Under this largest window, you will see an open Terminal window (titled "bash - <your-project-name>"), and another tab with the JavaScript REPL.

We will make use of Node and npm to install the latest version of Bootstrap via the command line (the readily open Bash Terminal). Both Node and npm come preinstalled in Cloud9 IDE.

Note

In Windows, navigate to the folder where you want to install Bootstrap 4, and then simply Shift + right-click inside it, and choose Open command window here.

How to do it...

  1. Inspect the versions of Node and npm installed on our virtual machine:

Note

In Windows, you can check the Node version with node -v, and npm version with npm -v.

  1. Inspect the available versions of Bootstrap to be installed:

The preceding command shows us that we can either install Bootstrap 3 (latest stable version) or Bootstrap 4 (latest alpha version); we will install Bootstrap 4.

  1. To install the latest alpha version of Bootstrap 4, run the following command:

Running the preceding command will almost instantly install the newest version of Bootstrap 4 in our node_modules directory. Inspect the directory's contents with ll (c9), or dir (Windows).

  1. Navigate to the node_modules/bootstrap folder:
      cd node_modules/bootstrap
  1. Install all the dependencies via npm install:
      npm install

After running the npm install command, a number of dependencies will be installed, just as listed in the package.json file. The installation will take some time. The reason why it takes so long is mostly due to the installation of the PhantomJS headless browser, which is used for testing in Bootstrap 4.

Once the installation process is completed, you will be greeted with a large number of folders and files. There are about 40 folders inside the node_modules folder. These folders house specific dependencies, such as grunt-sass or eslint. All of these dependencies are located inside the node_modules/bootstrap/node_modules path.

Here is the structure of the files installed using the npm approach:

After the installation is completed, the dist folder contains all the CSS and JavaScript needed to run a website.

Note

The dist folder is located at node_modules/bootstrap/dist.

All that is left now is to add HTML pages, and correctly reference the styles and scripts from the dist folder.

 

Installing Bootstrap 4 to Cloud9 IDE via Git


There is an alternative approach to install Bootstrap via npm and then by running the npm install command. This alternative involves downloading the latest Bootstrap release from the official GitHub repository. Contrary to the npm installation approach, this installation contains many additional files and folders, for example, the nuget folder. This means that you have downloaded all the available tools for all the platforms supported by Bootstrap. Depending on what you are trying to accomplish, installing via Git might be your preferred approach, as it gives you more options out of the box.

Getting ready

The process starts similarly to the previous recipe. You begin by clicking on Create a new workspace at the Cloud9 IDE dashboard.

Note

Alternatively, for Windows, you can follow along using the exact same commands below starting from the tip in step 3, and then from step 6 , provided that you use Cygwin or Git Bash for Windows to execute those commands.

How to do it...

  1. Fill out the Workspace name and Description.

Note

If you are following this recipe in Windows, start from step 3.

  1. In the Clone from Git or Mercurial URL input field, enter the address of the official Bootstrap repo on GitHub at https://github.com/twbs/bootstrap:

  2. Click on Create workspace. After clicking on Create workspace, a new container will be spun up. Once the environment is ready, you'll be greeted with the tree structure of Bootstrap 3.3.7, cloned from GitHub.

Note

Windows users should open Cygwin or Git Bash in the folder where you plan to install Bootstrap 4 via git. Execute the git clone https://github.com/twbs/bootstrap command. Type dir to see the current directory structure. You should see only one directory, titled bootstrap. Go into that directory by running the cd bootstrap command. Then skip step 4 and go to step 5.

  1. Run git fetch:
      git fetch
  1. Checkout the v4-dev branch:
      git checkout v4-dev

Running the preceding command will result in the following notifications in Bash:

         Branch v4-dev set up to track remote branch v4-dev from
         origin. Switched to a new branch 'v4-dev'

In other words, you have now switched to a branch that has the latest installation of Bootstrap 4.

  1. Install grunt-cli:
      npm install -g grunt-cli
  1. Run the package.json file:
      npm install

Running the preceding command will install PhantomJS, as well as a number of dependencies. At this point, we have the dist folder available with all the compiled .css and .js files. However, to be able to work with Bootstrap docs, we still need to install Bundler and Jekyll, which is explained in the next recipe.

 

Installing Bootstrap 4 Jekyll-powered docs


In this recipe, you will see how easy it is to install a copy of the official Bootstrap 4 docs. Running a local copy of the official Bootstrap documentation is a great way to experiment with the available Sass variables, as we will see later in this chapter.

Note

Windows users, you need to have Ruby, Jekyll, and Bundler installed. If you already have them on your system, and providing that you have completed the previous recipe, there are just a few more things to do to run the Jekyll docs. With your console pointing to chapter3/start/recipe3/bootstrap, run this command: gem install nokogiri -v 1.7.2. Next, run bundle exec jekyll build. This command will build your Jekyll site into ./_gh_pages. Run cd _gh_pages, then run jekyll serve --watch. Open your own local copy of Bootstrap docs at http://127.0.0.1:4000.

Getting ready

In order to follow this recipe successfully, you should first install Bootstrap 4 via Git. Thus, this recipe assumes that you have a running environment in Cloud9 IDE, and that you have a complete Bootstrap 4 installation as explained in the previous recipe.

How to do it...

  1. Verify that Ruby is preinstalled, and Jekyll is not:
      which ruby; which jekyll

This command will return only the location of Ruby on your VM. Thus, Jekyll needs to be installed.

  1. To install Jekyll, you need to install Bundler first:
      gem install bundler
  1. Now run bundle install, which will install Jekyll:

      bundle install
  1. Verify that Jekyll is installed:

      bundle show jekyll
  1. Serve Bootstrap 4 Jekyll-powered docs on Cloud9 IDE:

      bundle exec jekyll serve --host $IP --port $PORT --baseurl ''

Upon running this command, a notification will pop up with a link to preview the running webpage. Click on the link and choose one of the display options:

  1. Click on the link, and your very own copy of the Bootstrap docs will appear:

 

Customizing the styles of Bootstrap 4 docs


In the previous recipe, we built our own copy of Bootstrap 4 docs, running on Jekyll. In this recipe, we will see how to change the styling of our Bootstrap 4 docs by making simple changes to Sass variables.

Getting ready

For this recipe to work, you need to complete the previous two recipes, Installing Bootstrap 4 to c9 IDE using npm and Installing Bootstrap 4 to c9 IDE via git. The following steps will show you how to tweak the look of the docs by changing some of the Sass variables in the scss folder.

How to do it...

  1. Stop the running Jekyll server by clicking inside the Bash console tab and using Ctrl + C.
  2. Navigate to the scss folder and open the _variables.scss file:
      cd && cd workspace/scss && c9 _variables.scss

Note

In Windows, the path is ../bootstrap/scss/.

  1. Find the Sass variable $enable-rounded, and uncomment the line it is on, so that it looks like this:
      // $enable-rounded: true !default;
  1. On the very next line, paste in the following code:
      $enable-rounded: false !default;

Note

In Sass, using !default is like adding an unless this is already assigned qualifier to a variable. Thus, if you are overriding variables in some other file, make sure that there is no !default after the changed value of false and save the file.

  1. Still in console, change directory into the scss folder by running cd scss command. Then, run the following command:
      sass bootstrap.scss ../dist/css/bootstrap.css

This command will recompile SCSS into CSS for Bootstrap docs.

Note

In Windows, make sure that you run the preceding command from the ../bootstrap/ folder, that is the root, as cloned earlier using git. On c9.io, you can utilize multiple Bash console tabs, so there is no need to renavigate to root.

  1. Go back out from the scss folder, by running cd ... Back in the console tab, run the following command:
      bundle exec jekyll serve --watch --host $IP --port $PORT --  
      baseurl ''

When you refresh the webpage, it will now show the homepage with the Download Bootstrap button with sharp edges, instead of rounded ones, as seen in the following screenshot:

  1. Back in the _variables.scss file, override the default values by adding more changes:
      $white: #ddd;
      $enable-rounded: false;
      $spacer: 8rem;
      $font-size-base: 2rem;

You should probably make use of your code editor's search and replace function to complete this step. Once you have completed the step, make sure that you save the file.

  1. Recompile SCSS again by pointing your console to the scss folder with cd scss, then running the command from step 6 once again:
      sass bootstrap.scss ../dist/css/bootstrap.css
  1. Rebuild Jekyll by running:
      bundle exec jekyll build; 
  1. Go into _gh_pages and run Jekyll server:
      jekyll serve --watch --host $IP --port $PORT --baseurl '' 

This should result in the following changes on the docs website:

 

Making custom Grunt tasks in Bootstrap 4


To understand how to better work with a build tool such as Grunt, in this recipe we will customize the available Gruntfile.js and package.json. We will perform these changes without physically deleting these important files from the default installation. That way, we will be able to play around with customization and not lose the original files.

Getting ready

To start working on this recipe, we first need to navigate to the workspace folder, and rename the original Gruntfile.js and package.json:

      cd && cd workspace
      mv Gruntfile.js Gruntfile.jsORIGINAL
      mv package.json package.jsonORIGINAL

Now, we are ready to create new versions of these two files and add a custom Grunt task.

How to do it...

  1. Let's create new files:
      cd && cd workspace
      touch Gruntfile.js package.json
  1. Open the package.json file:
      c9 package.json

Note

An important thing to note is that if you had the old package.json file open before, during, and after the file renaming using the mv command, using the c9 <filename> command might point to the tab that was not closed, and show the old version of the file. Feel free to close this file's tab by middle-clicking on it (this works just like browser tabs, at least on c9.io running in Chrome).

  1. The package file is completely empty, so let's add some code to it:
      {
        "name": "customGrunt",
        "version": "",
        "devDependencies": {
          "grunt": "~1.0.1"
        }
      }

What are we doing in the package.json file? We are giving our package just some key:value pairs. Specifically, we are giving it a name, a version, and devDependencies. Right now, only the devDependency grunt is listed.

  1. Now we will add another plugin, grunt-contrib-copy, by typing the following command in our Bash console:
      npm install grunt-contrib-copy --save-dev

Now, we can see that the grunt-contrib-copy plugin has been added to the list of devDependencies in our custom package.json:

      {
        "name": "customGrunt",
        "version": "",
        "devDependencies": {
          "grunt": "~1.0.1",
          "grunt-contrib-copy": "^1.0.0"
        }
      }

More information about this plugin can be found at https://www.npmjs.com/package/grunt-contrib-copy. In a nutshell, this plugin copies files as we specify.

  1. Now that we have prepared our package.json file, we can tell Grunt how to use it, by coding Gruntfile.js. We will begin by opening the currently empty Gruntfile.js:
      c9 Gruntfile.js
  1. We will add the following code to our Gruntfile.js:
      'use strict';
      module.exports = function (grunt) {
        grunt.initConfig({
          pkg: grunt.file.readJSON('package.json'),

          // Define the copy task
          copy: {
            main: {
              expand: true,
              src: 'dist/css/bootstrap.css',
              dest: 'copy',
            },
          },
        });

        grunt.loadNpmTasks("grunt-contrib-copy");
        grunt.registerTask("default", ['copy']);
      };

Note

If you need a detailed explanation of how the above Gruntfile.js code works, take a look at the How it works… section.

  1. Finally, it is time to run our default Grunt task, with verbose logging:
      grunt -v

Running the preceding command will create a new folder and will copy the bootstrap.css file in the workspace/copy/dist/css/bootstrap.css

path.

  1. Now that we have a basic understanding of just how Grunt runs its tasks, as well as how to modify its tasks to our liking, let's undo the changes we did. However, we will still keep our experimental files, just to have them handy if needed. What follows are the commands used to achieve this. The following commands will get to the root, navigate to /workspace, and make a new folder called GruntExperiment:
      cd; cd workspace; mkdir GruntExperiment
  1. Now, let's move our custom Gruntfile.js and package.json files, with the following two commands:

  1. Finally, we need to rename our original files to their original names, running the following commands (note that there are two commands here, for two files; each command was split on two rows so they can fit this page width):
      mv node_modules/bootstrap/Gruntfile.jsORIGINAL 

         node_modules/bootstrap/Gruntfile.js;
      mv node_modules/bootstrap/package.jsonORIGINAL 
         node_modules/bootstrap/package.json

How it works...

In this recipe, we have provided some custom code needed for a very simple Gruntfile.js file to work in step 6 . What follows is the breakdown of what the code does.

On line 1, we use the strict mode. On line 3, we call the grunt module. Line 4 instructs grunt to read our package.json file. Lines 7-13 specify the copy task. Line 17 is the entry point that registers the 'copy' task as the default task.

 

Comparing Bootstrap 4 versions with Bower


In this recipe, we will see how to have a fine-grained view of the changes between Bootstrap 4 versions, using Bower. We will first install Bower, and then utilize Git to make comparisons.

Getting ready

To begin with, all we need to do is make a new project on Cloud9 IDE, without cloning a repository.

How to do it...

  1. Install bower using npm:
      npm install -g bower
  1. Verify the bower installation:
      which bower && bower -v

Note

Note that both commands should return some values.

  1. Install Bootstrap 4 alpha 5 (this is not a typo!):
      bower install bootstrap#v4.0.0-alpha.5

Note

We are installing an older version on purpose. This will be explained in the next steps.

  1. See the list of the installed dependencies:
      bower list

The preceding command will print out the status of your project's dependencies, including the available update to the currently installed Bootstrap 4 alpha 5.

  1. Initialize git in root:
      cd && cd workspace;
git init
  1. Stage the files into git's staging area:
      git add --all
  1. Commit the changes with a message:
      git commit -m “Add B4, alpha 5”
  1. Upgrade Bootstrap 4 to alpha 6 with bower:
      bower install bootstrap#v4.0.0-alpha.6

Note

To install this update, Windows users will have to use the command prompt (rather than Git Bash for Windows). When prompted for answer, type "2" and then press ENTER.

  1. Now, using git diff, we have at our fingertips the full view of changes that happened between alpha 5 and alpha 6 versions of Bootstrap 4. However, it is not feasible to simply use a blanket git diff command because too many changes are made to too many files between each version. A much better strategy is to use the git diff --stat, with the --stat flag giving us a nice overall idea of the changes, as well as which files had the most changes and which had the least. The following screenshot lists only the beginning of the output of the git diff --stat command, and does not include all the files affected, but it gives us a nice visual overview of changes made between alpha versions 5 and 6:

Note

For Windows users, before listing the result of the git diff --stat command, Windows command prompt will throw a bunch of errors--just use the Page Down button to move past them.

  1. Now we can inspect only the files that we are interested in, for example, the following command:
      git diff bower_components/bootstrap/scss/_alert.scss

The preceding command will show us the changes made only in the _alert.scss partial, between Bootstrap 4 Alpha 5 and Alpha 6 versions. In the following screenshot, we can see one of the changes made to this file:

  1. With this approach, it is also really simple to track the changes to the _alert.scss file in the previous versions of Bootstrap 4 alpha. For example, we can downgrade our Bootstrap 4 installation with the help of Bower, and then repeat our git diff for the _alert.scss file only, by running the following commands:
      bower install bootstrap#4.0.0-alpha.4
      git diff bower_components/bootstrap/scss/_alert.scss

With this recipe, we are able to have complete, fine-grained control of observing the changes made to the framework through its versions. This is an amazing approach to understand the changes that occurred to specific components between different versions of the framework. It can help us understand why bugs occurred in our code, avoid pitfalls when working with legacy code, and learn the approaches taken by the Bootstrap contributors and how to better work with Sass in Bootstrap.

 

Installing Bootstrap 4 to our Cloud9 IDE with Bower


In this recipe, we will see how to install the newest version of Bootstrap 4 using Bower.

Getting ready

Just like the previous recipe, we will make a new project on Cloud9 IDE without cloning a repo.

How to do it...

  1. Install bower using npm:
      npm install -g bower
  1. Verify the bower installation:
      which bower && bower -v

Note

Note that both commands should return some values.

  1. Install Bootstrap 4 alpha 6:
      bower install bootstrap#v4.0.0-alpha.6
  1. Navigate to the bootstrap folder:
      cd && cd workspace/bower_components/bootstrap
  1. Run npm install to install all the dependencies:
      npm install

Note

Note that this will take a while.

  1. Run grunt verbose:
      grunt -v

Now, you can easily reference the dist folder with the necessary styles and scripts for your Bootstrap website to work.

About the Author

  • Ajdin Imsirovic

    Ajdin Imsirovic is a full-stack web developer who has published several courses on the subject of web design and web development. He has also authored three books, Bootstrap 4 Cookbook, Elm Web Development, and Vue.js Quick Start Guide. In his fourth book, Vue CLI 3 Quick Start Guide, he introduces readers to the rich ecosystem of frontend tooling and best practices.

    Browse publications by this author

Latest Reviews

(6 reviews total)
rapide et low cost.... Ouvrage de qualité technique....
I was missing a delivery. I contacted them and a new copy was dispatched the same day..Excellent service.
Satisface mi necesidad actual

Recommended For You

Bootstrap 4 Cookbook
Unlock this book and the full library for FREE
Start free trial