18 min read

In this article by Bass Jobsen author of the book Bootstrap 4 Site Blueprints explains 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 the most standard UI conventions. Its ready-made, community-tested combination of HTML markup, CSS styles, and JavaScript plugins greatly speed up the task of developing a frontend web interface, and it yields a pleasing result out of the gate. With the fundamental elements in place, we can customize the design on top of a solid foundation.

(For more resources related to this topic, see here.)

However, 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 followed 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, including from semantic markup, mobile-first design, and performance-optimized assets, require extra time and effort for implementation.

Quantity and quality

If handled well, I feel that Bootstrap is a boon for the web development community in terms of quality and efficiency. Since developers are attracted to the web development framework, they become part of a coding community that draws them increasingly to the current best practices. From the start, Bootstrap has encouraged the 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 took responsive design into the mainstream, ensuring that its interface elements could travel well across devices, from desktops to tablets to handhelds.

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

  • The responsive grid was now mobile-first friendly
  • Icons now utilize web fonts and, thus, were mobile- and retina-friendly
  • With the drop of the support for IE7, markup and CSS conventions were now leaner and more efficient
  • Since version 3.2, autoprefixer was required to build Bootstrap
  • This article is about the v4.0 release. This release contains many improvements and also some new components, while some other components and plugins are dropped. In the following overview, you will find the most important improvements and changes in Bootstrap 4:
    • Less (Leaner CSS) has been replaced with Sass.
    • CSS code has been refactored to avoid tag and child selectors.
    • There is an improved grid system with a new grid tier to better target the mobile devices.
    • The navbar has been replaced.
    • It has an opt-in flexbox support.
  • It has a new HTML reset module called Reboot. Reboot extends Nicholas Galagher’s CSS normalize and handles the box-sizing: border-box declarations.
  • jQuery plugins are written in ES6 now and come with a UMD support.
  • There is an improved auto-placement of tooltips and popovers, thanks to the help of a library called Tether.
  • It has dropped the support for Internet Explorer 8, which enables us to swap pixels with rem and em units.
  • It has added the Card component, which replaces the Wells, thumbnails, and Panels in earlier versions.
  • It has dropped the icons in the font format from the Glyphicon Halflings set.
  • The Affix plugin is dropped, and it can be replaced with the position: sticky polyfill (https://github.com/filamentgroup/fixed-sticky).

The power of Sass

When working with Bootstrap, there is the power of Sass to consider. Sass is a preprocessor for CSS. It extends the CSS syntax with variables, mixins, and functions and helps you in DRY (Don’t Repeat Yourself) coding your CSS code. Sass has originally been written in Ruby. Nowadays, a fast port of Sass written in C++, called libSass, is available. Bootstrap uses the modern SCSS syntax for Sass instead of the older indented syntax of Sass.

Using Bootstrap CLI

You will be introduced to Bootstrap CLI. Instead of using Bootstrap’s bundled build process, you can also start a new project by running the Bootstrap CLI.

Bootstrap CLI is the command-line interface for Bootstrap 4. It includes some built-in example projects, but you can also use it to employ and deliver your own projects.

You’ll need the following software installed to get started with Bootstrap CLI:

  • Node.js 0.12+: Use the installer provided on the NodeJS website, which can be found at http://nodejs.org/
  • With Node installed, run [sudo] npm install -g grunt bower
  • Git: Use the installer for your OS
  • Windows users can also try Git

Gulp is another task runner for the Node.js system. Note that if you prefer Gulp over Grunt, you should install gulp instead of grunt with the following command:

[sudo] npm install -g gulp bower

The Bootstrap CLI is installed through npm by running the following command in your console:

npm install -g bootstrap-cli

This will add the bootstrap command to your system.

Preparing a new Bootstrap project

After installing the Bootstrap CLI, you can create a new Bootstrap project by running the following command in your console:

bootstrap new --template empty-bootstrap-project-gulp

Enter the name of your project for the question “What’s the project called? (no spaces)“. A new folder with the project name will be created. After the setup process, the directory and file structure of your new project folder should look as shown in the following figure:

The project folder also contains a Gulpfile.js file. Now, you can run the bootstrap watch command in your console and start editing the html/pages/index.html file. The HTML templates are compiled with Panini. Panini is a flat file compiler that helps you to create HTML pages with consistent layouts and reusable partials with ease.

You can read more about Panini at http://foundation.zurb.com/sites/docs/panini.html.

Responsive features and breakpoints

Bootstrap has got four breakpoints at 544, 768, 992, and 1200 pixels by default. At these breakpoints, your design may adapt to and target specific devices and viewport sizes. Bootstrap’s mobile-first and responsive grid(s) also use these breakpoints. You can read more about the grids later on.

You can use these breakpoints to specify and name the viewport ranges. The extra small (xs) range is for portrait phones with a viewport smaller than 544 pixels, the small (sm) range is for landscape phones with viewports smaller than 768pixels, the medium (md) range is for tablets with viewports smaller than 992pixels, the large (lg) range is for desktop with viewports wider than 992pixels, and finally the extra-large (xl) range is for desktops with a viewport wider than 1200 pixels. The breakpoints are in pixel values, as the viewport pixel size does not depend on the font size and modern browsers have already fixed some zooming bugs.

Some people claim that em values should be preferred.

To learn more about this, check out the following link: http://zellwk.com/blog/media-query-units/.

Those who still prefer em values over pixels value can simply change the $grid-breakpointsvariable declaration in the scss/includes/_variables.scssfile. To use em values for media queries, the SCSS code should as follows:

$grid-breakpoints: (
  // Extra small screen / phone
  xs: 0,
  // Small screen / phone
  sm: 34em, // 544px
  // Medium screen / tablet
  md: 48em, // 768px
  // Large screen / desktop
  lg: 62em, // 992px
  // Extra large screen / wide desktop
  xl: 75em //1200px
);

Note that you also have to change the $container-max-widths variable declaration. You should change or modify Bootstrap’s variables in the local scss/includes/_variables.scss file, as explained at http://bassjobsen.weblogs.fm/preserve_settings_and_customizations_when_updating_bootstrap/. This will ensure that your changes are not overwritten when you update Bootstrap.

The new Reboot module and Normalize.css

When talking about cascade in CSS, there will, no doubt, be a mention of the browser default settings getting a higher precedence than the author’s preferred styling. In other words, anything that is not defined by the author will be assigned a default styling set by the browser. The default styling may differ for each browser, and this behavior plays a major role in many cross-browser issues. To prevent these sorts of problems, you can perform a CSS reset. CSS or HTML resets set a default author style for commonly used HTML elements to make sure that browser default styles do not mess up your pages or render your HTML elements to be different on other browsers.

Bootstrap uses Normalize.css written by Nicholas Galagher. Normalize.css is a modern, HTML5-ready alternative to CSS resets and can be downloaded from http://necolas.github.io/normalize.css/. It lets browsers render all elements more consistently and makes them adhere to modern standards. Together with some other styles, Normalize.css forms the new Reboot module of Bootstrap.

Box-sizing

The Reboot module also sets the global box-sizing value from content-box to border-box. The box-sizing property is the one that sets the CSS-box model used for calculating the dimensions of an element. In fact, box-sizing is not new in CSS, but nonetheless, switching your code to box-sizing: border-box will make your work a lot easier. When using the border-box settings, calculation of the width of an element includes border width and padding. So, changing the border width or padding of an element won’t break your layouts.

Predefined CSS classes

Bootstrap ships with predefined CSS classes for everything. You can build a mobile-first responsive grid for your project by only using div elements and the right grid classes. CSS classes for styling other elements and components are also available. Consider the styling of a button in the following HTML code:

<button class="btn btn-warning">Warning!</button>

Now, your button will be as shown in the following screenshot:

You will notice that Bootstrap uses two classes to style a single button. The first is the .btn class that gives the button the general button layout styles. The second class is the .btn-warning class that sets the custom colors of the buttons.

Creating a local Sass structure

Before we can start with compiling Bootstrap’s Sass code into CSS code, we have to create some local Sass or SCSS files. First, create a new scss subdirectory in your project directory. In the scss directory, create your main project file called app.scss.

Then, create a new subdirectory in the new scss directory named includes. Now, you will have to copy bootstrap.scss and _variables.scss from the Bootstrap source code in the bower_components directory to the new scss/includes directory as follows:

cp bower_components/bootstrap/scss/bootstrap.scss scss/includes/_bootstrap.scss
cp bower_components/bootstrap/scss/_variables.scss scss/includes/

You will notice that the bootstrap.scss file has been renamed to _bootstrap.scss, starting with an underscore, and has become a partial file now.

Import the files you have copied in the previous step into the app.scss file, as follows:

@import "includes/variables";
@import "includes/bootstrap";

Then, open the scss/includes/_bootstrap.scss file and change the import part for the Bootstrap partial files so that the original code in the bower_components directory will be imported here. Note that we will set the include path for the Sass compiler to the bower_components directory later on. The @import statements should look as shown in the following SCSS code:

// Core variables and mixins
@import "bootstrap/scss/variables";
@import "bootstrap/scss/mixins";

// Reset and dependencies
@import "bootstrap/scss/normalize";

You’re importing all of Bootstrap’s SCSS code in your project now. When preparing your code for production, you can consider commenting out the partials that you do not require for your project.

Modification of scss/includes/_variables.scss is not required, but you can consider removing the !default declarations because the real default values are set in the original _variables.scss file, which is imported after the local one.

Note that the local scss/includes/_variables.scss file does not have to contain a copy of all of the Bootstrap’s variables. Having them all just makes it easier to modify them for customization; it also ensures that your default values do not change when you are updating Bootstrap.

Setting up your project and requirements

For this project, you’ll use the Bootstrap CLI again, as it helps you create a setup for your project comfortably. Bootstrap CLI requires you to have Node.js and Gulp already installed on your system.

Now, create a new project by running the following command in your console:

bootstrap new

Enter the name of your project and choose the An empty new Bootstrap project. Powered by Panini, Sass and Gulp. template. Now your project is ready to start with your design work. However, before you start, let’s first go through the introduction to Sass and the strategies for customization.

The power of Sass in your project

Sass is a preprocessor for CSS code and is an extension of CSS3, which adds nested rules, variables, mixins, functions, selector inheritance, and more.

Creating a local Sass structure

Before we can start with compiling Bootstrap’s Sass code into CSS code, we have to create some local Sass or SCSS files. First, create a new scss subdirectory in your project directory. In the scss directory, create your main project file and name it app.scss.

Using the CLI and running the code from GitHub

Install the Bootstrap CLI using the following commands in your console:

[sudo] npm install -g gulp bower
npm install bootstrap-cli --global

Then, use the following command to set up a Bootstrap 4 Weblog project:

bootstrap new --repo https://github.com/bassjobsen/bootstrap-weblog.git

The following figure shows the end result of your efforts:

Turning our design into a WordPress theme

WordPress is a very popular CMS (Content Management System) system; it now powers 25 percent of all sites across the web. WordPress is a free and open source CMS system and is based on PHP. To learn more about WordPress, you can also visit Packt Publishing’s WordPress Tech Page at https://www.packtpub.com/tech/wordpress.

Now let’s turn our design into a WordPress theme. There are many Bootstrap-based themes that we could choose from. We’ve taken care to integrate Bootstrap’s powerful Sass styles and JavaScript plugins with the best practices found for HTML5. It will be to our advantage to use a theme that does the same. We’ll use the JBST4 theme for this exercise. JBST4 is a blank WordPress theme built with Bootstrap 4.

Installing the JBST 4 theme

Let’s get started by downloading the JBST theme. Navigate to your wordpress/wp-content/themes/ directory and run the following command in your console:

git clone https://github.com/bassjobsen/jbst-4-sass.git jbst-weblog-theme

Then navigate to the new jbst-weblog-theme directory and run the following command to confirm whether everything is working:

npm install
gulp

Download from GitHub

You can download the newest and updated version of this theme from GitHub too. You will find it at https://github.com/bassjobsen/jbst-weblog-theme.

JavaScript events of the Carousel plugin

Bootstrap provides custom events for most of the plugins’ unique actions. The Carousel plugin fires the slide.bs.carousel (at the beginning of the slide transition) and slid.bs.carousel (at the end of the slide transition) events. You can use these events to add custom JavaScript code. You can, for instance, change the background color of the body on the events by adding the following JavaScript into the js/main.js file:

$('.carousel').on('slide.bs.carousel', function () {
  $('body').css('background-color','#'+(Math.random()*0xFFFFFF<<0).toString(16));
});

You will notice that the gulp watch task is not set for the js/main.js file, so you have to run the gulp or bootstrap watch command manually after you are done with the changes.

For more advanced changes of the plugin’s behavior, you can overwrite its methods by using, for instance, the following JavaScript code:

!function($) {
var number = 0;
    var tmp = $.fn.carousel.Constructor.prototype.cycle;
    $.fn.carousel.Constructor.prototype.cycle = function (relatedTarget) {  
        // custom JavaScript code here
        number = (number % 4) + 1;
        $('body').css('transform','rotate('+ number * 90 +'deg)');
        tmp.call(this); // call the original function
    };

}(jQuery);

The preceding JavaScript sets the transform CSS property without vendor prefixes. The autoprefixer only prefixes your static CSS code. For full browser compatibility, you should add the vendor prefixes in the JavaScript code yourself.

Bootstrap exclusively uses CSS3 for its animations, but Internet Explorer 9 doesn’t support the necessary CSS properties.

Adding drop-down menus to our navbar

Bootstrap’s JavaScript Dropdown Plugin enables you to create drop-down menus with ease. You can also add these drop-down menus in your navbar too.

Open the html/includes/header.html file in your text editor. You will notice that the Gulp build process uses the Panini HTML compiler to compile our HTML templates into HTML pages. Panini is powered by the Handlebars template language. You can use helpers, iterations, and custom data in your templates. In this example, you’ll use the power of Panini to build the navbar items with drop-down menus.

First, create a html/data/productgroups.yml file that contains the titles of the navbar items:

  • Shoes
  • Clothing
  • Accessories
  • Women
  • Men
  • Kids
  • All Departments

The preceding code is written in the YAML format. YAML is a human-readable data serialization language that takes concepts from programming languages and ideas from XML; you can read more about it at http://yaml.org/.

Using the data described in the preceding code, you can use the following HTML and template code to build the navbar items:

<ul class="nav navbar-nav navbar-toggleable-sm collapse" id="collapsiblecontent">
  {{#each productgroups}}
<li class="nav-item dropdown {{#ifCond this 'Shoes'}}active{{/ifCond}}">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
      {{ this }}
</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Separated link</a>
</div>
</li>
  {{/each}}
</ul>

The preceding code uses a (for) each loop to build the seven navbar items; each item gets the same drop-down menu. The Shoes menu got the active class. Handlebars, and so Panini, does not support conditional comparisons by default. The if-statement can only handle a single value, but you can add a custom helper to enable conditional comparisons. The custom helper, which enables us to use the ifCond statement can be found in the html/helpers/ifCond.js file. Read my blog post, How to set up Panini for different environment, at http://bassjobsen.weblogs.fm/set-panini-different-environments/, to learn more about Panini and custom helpers.

The HTML code for the drop-down menu is in accordance with the code for drop-down menus as described for the Dropdown plugin at http://getbootstrap.com/components/dropdowns/.

The navbar collapses for smaller screen sizes. By default, the drop-down menus look the same on all grids:

Now, you will use your Bootstrap skills to build an Angular 2 app. Angular 2 is the successor of AngularJS. You can read more about Angular 2 at https://angular.io/. It is a toolset for building the framework that is most suited to your application development; it lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop. Angular is maintained by Google and a community of individuals and corporations.

I have also published the source for Angular 2 with Bootstrap 4 starting point at GitHub. You will find it at the following URL: https://github.com/bassjobsen/angular2-bootstrap4-website-builder.

You can install it by simply running the following command in your console:

git clone https://github.com/bassjobsen/angular2-bootstrap4-website-builder.git yourproject

Next, navigate to the new folder and run the following commands and verify that it works:

npm install
npm start

Other tools to deploy Bootstrap 4

A Brunch skeleton using Bootstrap 4 is available at https://github.com/bassjobsen/brunch-bootstrap4. Brunch is a frontend web app build tool that builds, lints, compiles, concatenates, and shrinks your HTML5 apps.

Read more about Brunch at the official website, which can be found at http://brunch.io/. You can try Brunch by running the following commands in your console:

npm install -g brunch
brunch new -s https://github.com/bassjobsen/brunch-bootstrap4

Notice that the first command requires administrator rights to run. After installing the tool, you can run the following command to build your project:

brunch build

The preceding command will create a new public/index.html file, after which you can open it in your browser. You’ll find that it look like this:

Yeoman

Yeoman is another build tool. It’s a command-line utility that allows the creation of projects utilizing scaffolding templates, called generators. A Yeoman generator that scaffolds out a frontend Bootstrap 4 web app can be found at the following URL: https://github.com/bassjobsen/generator-bootstrap4

You can run the Yeoman Bootstrap 4 generator by running the following commands in your console:

npm install -g yo
npm install -g generator-bootstrap4
yo bootstrap4
grunt serve

Again, note that the first two commands require administrator rights.

The grunt serve command runs a local web server at http://localhost:9000. Point your browser to that address and check whether it look as follows:

Summary

Beyond this, there are a plethora of resources available for pushing further with Bootstrap. The Bootstrap community is an active and exciting one. This is truly an exciting point in the history of frontend web development. Bootstrap has made a mark in history, and for a good reason. Check out my GitHub pages at http://github.com/bassjobsen for new projects and updated sources or ask me a question on Stack Overflow (http://stackoverflow.com/users/1596547/bass-jobsen).

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here