Home Web Development Bootstrap 4 Site Blueprints - Second Edition

Bootstrap 4 Site Blueprints - Second Edition

By Ian Whitney , David Cochran
books-svg-icon Book
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with Bootstrap
About this book
Packed with trade secrets, this second edition is your one-stop solution to creating websites that will provide the best experience for your users. We cover six popular, real-world examples, where each project teaches you about the various functionalities of Bootstrap 4 and their implementation. The book starts off by getting you up and running with the new features of Bootstrap 4 before gradually moving on to customizing your blog with Bootstrap and SASS, building a portfolio site, and turning it into a WordPress theme. In the process, you will learn to recompile Bootstrap files using SASS, design a user interface, and integrate JavaScript plugins. Towards the end of the book, you will also be introduced to integrating Bootstrap 4 with popular application frameworks such as Angular 2, Ruby on Rails, and React.
Publication date:
October 2016
Publisher
Packt
Pages
404
ISBN
9781785889653

 

Chapter 1. Getting Started with Bootstrap

Bootstrap's popularity as a front-end 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 plugins greatly accelerates 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.

Bootstrap uses Grunt for its CSS and JavaScript build system, and Jekyll for the written documentation. Grunt is a JavaScript task runner for Node.js. Other tools and technologies can also be used to build Bootstrap. In this book you will get introduced to some alternative solutions to build Bootstrap.

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. In this chapter you will get introduced to Bootstrap and will learn:

Creating a solid HTML5 markup structure with many current best practices baked-in

  • Setting up a new Bootstrap project with Bootstrap CLI

  • Building collapsing content into your project pages

  • Creating a navbar for page navigation

  • Turning your navbar into a responsive component

 

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.

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 support for IE7, markup and CSS conventions were now leaner and more efficient.

  • Since version 3.2, the autoprefixer was required to build Bootstrap.

  • This book is about the v4.0 release. This release contains many improvements and also some new components while other components and plugins are dropped. In the overview below, you will find the most important improvements and changes in Bootstrap 4:

    • Less (Leaner CSS) has been replaced with Sass

    • Refactoring of CSS code to avoid tag and child selectors

    • Improved grid system with a new grid tier to better target mobile devices

    • Replaced the navbar

    • Opt-in flexbox support

  • 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 UMD support.

  • Improved auto-placement of tooltips and popovers, thanks to the help of a library called Tether.

  • Dropped support for Internet Explorer 8 which enables us to swap pixels with rem and em units.

  • Added the Card component, which replaces the Wells, Thumbnails, and Panels in earlier versions.

  • Dropped the icons in font format from the Glyphicon Halflings set.

  • Dropped the Affix plugin, which 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 was originally 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 Sass's indented syntax.

Note

Those who work with CSS in their daily job and have some experience with functional programming language, won't find learning Sass very difficult. However, those who want to get more out of Sass should read my Sass and Compass Designer's Cookbook (https://www.packtpub.com/web-development/sass-and-compass-designers-cookbook) too.

In Bootstrap 4, Sass replaced Less. Less is another preprocessor for CSS. The Bootstrap team preferred Sass over Less, because of the increasingly large community of Sass developers. If you are used to Less and have to switch to Sass now, you should realize that Sass is more like a functional programming language in contrast to the more declarative nature of Less. In Sass you cannot use variables before declaring them first, so you have to modify your variables at the beginning of your code. Bootstrap's variables have default values which can be overwritten by declaring and assigning a new variable with the same name before the default declaration.

In contrast to Less, Sass does support if-else-then constructs and for and foreach loops.

When we move beyond merely applying classes to markup and take the next step to dig in and customize Bootstrap's SCSS 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 the compiled code

On http://getbootstrap.com/, you will find some button links which enable you to download the compiled code of Bootstrap. These downloads contain the compiled CSS and JavaScript code ready to use in your projects. The compiled code contains the CSS and JavaScript code for all of Bootstrap's components and features. Later on, you will learn to create a custom version of Bootstrap, which includes only those components and features that you really use.

Instead of the default code, you can also choose to download the Flexbox-enabled or grid-only versions.

The Flexbox enabled version

On http://getbootstrap.com/, you can also download a compiled version of Bootstrap with the optional Flexbox support already enabled. Since switching to the Flexbox version does not require any HTML changes, you will only have to change the CSS source.

The grid only versions

Bootstrap ships with a 12 column, responsive, and mobile first grid. People who only want to use the grid for their projects can download the grid only version. The grid only version provides the predefined grid classes and does not require any JavaScript. Those who only use the grid should add their own HTML reset which includes the box-sizing: borderbox setting as described in the Box-sizing section of this chapter.

Beside the predefined grid classes, you can also have the option of using Sass variables and mixins to create custom, semantic, and responsive page layouts.

Running Bootstrap from CDN

Instead of downloading your own copy of Bootstrap, you can also load it from CDN (Content Delivery Network) inside your projects. CDNs help to distribute bandwidth across multiple servers and allow users to download static content from a closer source.

Note

Bootstrap can be loaded from https://www.bootstrapcdn.com/. BootstrapCDN is powered by MaxCDN which can be found at https://www.maxcdn.com/.

Subresource Integrity (SRI)

CDN can be quite a risk, because others can get control over the CDN code and may inject arbitrary malicious content into files. You can prevent this risk by adding the integrity attribute to the <script> and <link> elements which loads the file from CDN. The integrity attribute should be set to a string with base64-encoded sha384 hash. You should also add the crossorigin attribute. The script element to load jQuery into your project from MaxCDN may look like the following:

<script   src="http://code.jquery.com/jquery-2.2.3.min.js"   integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="   crossorigin="anonymous"></script>

Note

You can read more about Subresource Integrity checking at https://www.w3.org/TR/SRI/.

 

Downloading Bootstrap's source files


There are many other ways to download Bootstrap, but not all ways of downloading Bootstrap are equal. For what follows, we must be sure to get the Sass 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, http://getbootstrap.com/. You will encounter the following screenshot:

Once there, the large Download source button is your friend. At least as of Version 4.0, this is the second largest button on the homepage of Bootstrap:

In case something should change, you can always follow the GitHub project link at https://github.com/twbs/bootstrap, and once at the GitHub repository, click on the Download ZIP button. Or run the following command in your console to clone the repo:

git clone https://github.com/twbs/bootstrap.git

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:

The preceding files contain not only Bootstrap's source files, including the SCSS code and EM6 code for the jQuery plugins, but also the files to set up Bootstrap's build process. Bootstrap is built with Grunt by default. 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. Notice that the source does not contain font files since the Glyphicon Halflings set has been dropped as described earlier. Bootstrap's default fonts are set by CSS only and do not require a font file.

While the exact contents of the repository will change over time, the main contents will remain relatively consistent. Most notably, in the scss folder, you will find all the important Sass 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), they are still available within the dist folder. The structure of the precompiled files will look like the following:

The umd folder in the preceding screenshot contains the plugin files ready to require() this file in a CommonJS environment. These files are UMD ready (Universal Module Definition). Both CommonJS and AMD are script loaders which ensure that different JavaScript components load in the right order and play nice together. The universal pattern of UMD supports both CommonJS and AMD.

As a bonus, you'll find the example HTML templates in the docs/examples folder. In fact, we'll use one of these examples to set up our first project template folder.

Other ways to download and integrate Bootstrap

Instead of directly downloading Bootstrap, you can also use other tool and package managers to get the files. In the overview below, you will find a list of commands and tools:

  • Install with npm: npm install bootstrap

  • Install with Meteor: meteor add twbs:bootstrap

  • Install with Composer: composer require twbs/bootstrap

  • Install with Bower: bower install bootstrap

  • Install with NuGet:

    • CSS: Install-Package bootstrap -Pre

    • Sass: Install-Package bootstrap.sass -Pre

 

Tooling setup


To use the Grunt file and run Bootstrap's documentation locally, you'll need a copy of Bootstrap's source files, Node, and Grunt. Use the following steps to start working with Bootstrap's build process:

  • Install the Grunt command line tools, grunt-cli, with npm install -g grunt-cli

  • Navigate to the root /bootstrap directory and run npm install to install our local dependencies listed in package.json

  • Install Ruby and install Bundler with gem install bundler, and finally run bundle install. This will install all Ruby dependencies, such as Jekyll and plugins

Now you can run the documentation locally by running the following command from the root /bootstrap directory in your console:

bundle exec jekyll serve

After the preceding step, the documentation and examples are available at http://localhost:/9010.

The HTML starter template

After downloading the Bootstrap source files, you can link the compiled CSS and JavaScript files from the dist folder to your HTML. You can do this by creating a new HTML template. Your HTML template should look like the following:

<!DOCTYPE html>
<html lang="en">
  <head>
  <!-- Required meta tags always come first -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css">
  </head>
  <body>
  <h1>Hello, world!</h1>
  <!-- jQuery first, then Bootstrap JS. -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.1.2/js/tether.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"></script>
  </body>
</html>

As seen above, your HTML code should start with the HTML5 doctype: <!DOCTYPE html>

Responsive meta tag

Because of the responsive and mobile first nature of Bootstrap, your HTML code should also contain a responsive meta tag in the head section which looks like the following:

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

The mobile first strategy of Bootstrap means that the code is optimized for mobile devices first. CSS media queries are used to add more features for larger screen sizes.

The X-UA-Compatible meta tag

The X-UA-Compatible is another important meta tag which should be added to the head section of your HTML template. It should look like the following:

<meta http-equiv="x-ua-compatible" content="ie=edge">

The preceding meta tag is forcing Internet Explorer to use its latest rendering mode.

Bootstrap's CSS code

Of course you should also link Bootstrap's CSS code to your HTML document, the example template above loads the CSS code from CDN. You can replace the CDN URI with your local copy found in the dist folder as follows:

<link rel="stylesheet" href="dist/css/bootstrap.min.css">

The JavaScript files

And finally, you should link the JavaScript files at the end of your HTML code for faster loading. Bootstrap's JavaScript plugin requires jQuery, so you have to load jQuery before the plugins. The popover and plugins also require the Tether library which requires jQuery too. Link Tether after jQuery and before the plugins. Your HTML should look like the following:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.1.2/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"></script>

Of course you can link local copies of the files instead of the CDN URIs too.

 

Using Bootstrap CLI


In this book 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 Node.js website, which can be found at the follow URL: https://nodejs.org/en/

  • With Node installed, run [sudo] npm install -g grunt bower

  • Git: Use the installer for your OS

  • Windows users can also try Git for Windows

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

[sudo] npm install -g gulp bower

You can read more about Gulp in Chapter 2, Creating Your Own Build Process with Gulp.

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 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 like that shown in the following screenshot:

The project folder also contains a Gulpfile.js file. In Chapter 2, Creating Your Own Build Process with Gulp, you can read how to set up a Bootstrap project with a Gulp build process yourself.

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 which 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.

Panini compiles the HTML templates into a single index.html file like the base template described in the preceding sections.

 

Setting up major structural elements


We're almost ready for page content. 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).

Run the bootstrap watch command, and your browser should open automatically on http://localhost:8080/. Then start editing the html/pages/index.html file; you can use your favorite text editor, and write down the following HTML code into it:

--- 
layout: default 
title: Home 
--- 
<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. Notice that the content you have added to the html/pages/index.html file is compiled into the html/layout/default.html layout template. The layout template contains the main HTML structure and links the compiled CSS and JavaScript code.

The JavaScript code has been linked at the end of the HTML code for faster performance. Notice that Gulp bundles jQuery, Tether, and the Bootstrap jQuery plugins into a single _site/js/app.jss  file. Loading jQuery on Tether from CDN is an alternative solution.

Providing a navbar markup

The compiled CSS code is already linked to the compiled HTML code and can be found in the _site/css folder. We'll learn how to customize the CSS with Sass 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. This leads to the following result, nested within our header element:

<header role="banner"> 
<nav class="navbar navbar-light bg-faded" role="navigation"> 
  <a class="navbar-brand" href="index.html">Navbar</a> 
  <ul class="nav navbar-nav"> 
    <li class="nav-item"> 
      <a class="nav-link active" href="#">Home <span class="sr-only">(current)</span></a> 
    </li> 
    <li class="nav-item"> 
      <a class="nav-link" href="#">Features</a> 
    </li> 
    <li class="nav-item"> 
      <a class="nav-link" href="#">Pricing</a> 
    </li> 
    <li class="nav-item"> 
      <a class="nav-link" href="#">About</a> 
    </li> 
  </ul> 
  <form class="form-inline pull-xs-right"> 
    <input class="form-control" type="text" placeholder="Search"> 
    <button class="btn btn-success-outline" type="submit">Search</button> 
  </form> 
</nav> 
</header> 

Save your results, and the browser will automatically refresh. You should now see Bootstrap's default navigation styles, and you'll also 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.

The CSS classes of the navbar

As you can see in the preceding navbar example, you can construct the navbar with standard HTML elements, such as the <nav>, <a> and <ul>, and Bootstrap's CSS classes.

First inspect the classes added to the <nav> element in the following snippet:

<nav class="navbar navbar-light bg-faded" role="navigation"></nav> 
 
The .nav class sets the basic styles for the navbar.

The .navbar-light and .navbar-dark classes set the color of the texts and links in the navbar. You should use the .navbar-light classes when the background color of the navbar has a light color and the .navbar-dark class for dark colored navbars.

Finally, the .bg-* classes set the background color of the navbar; you can use one of the following classes to do this: .bg-inverse, .bg-faded, .bg-primary, .bg-success, .bg-info, .bg-warning and .bg-danger. These classes are part of Bootstrap's contextual backgrounds and can also be used for other elements and components.

The title or heading of the navbar can be an <a> or <span> element with the .navbar-brand class.

The navbar items are built with an unnumbered list (<url>), wherein each list item (<li>) gets the .nav-item tag and contains an anchor (<a>) tag with the .navbar-link class. Active items not only have the .navbar-link class but also the .active class.

Finally, notice the .sr-only class in the following snippet of the navbar HTML code:

<span class="sr-only">(current)</span> 

HTML elements with the .sr-only class are only available for screen readers.

Note

More information about this can be found at http://a11yproject.com/posts/how-to-hide-content/.

Placement of the navbars

By default, navbars have rounded corners and are statically placed on the page. Special CSS classes can be used to fix the navbar at the top (.navbar-fixed-top) or bottom (.navbar-fixed-bottom) of the page or remove the rounded corners and set the z-index of the navbar (.nav bar-full). 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.

Adding collapsible content to the navbar

Bootstrap's collapsible plugin allows you to create collapsible content by simply using a <a> and <button> tag to toggle hidden content. You can add the toggle button to your navbar too.

First create your collapsible content and wrap it in a <div class="collapse"> with a unique id as follows:

<div class="collapse" id="collapsiblecontent"> 
Collapsible content 
</div> 

Then create the button with .navbar-toggler class and data-toggle and data-target attributes like that shown in the HTML code shown as follows:

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsiblecontent">
☰;
; </button>

In the above code snippet, the data-toggle attribute should be set to collapseto trigger the collapse plugin, and the data-target attribute should refer to the unique ID set for your collapsible content. Notice that the &#9776HTML code defines the so-called hamburger sign which looks like this:

Now you can bring the preceding codes together and place the button in the navbar. Write down the following HTML in the html/pages/index.html file and inspect the results in your browser:

<header> 
  <div class="collapse" id="collapsiblecontent"> 
    Collapsible content 
  </div> 
  <nav class="navbar navbar-light bg-faded" role="navigation"> 
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsiblecontent"> 
    ☰ 
  </button> 
 </nav> 
</header> 

If you are still running the bootstrap watch command, your browser should automatically reload. The result should look like that shown in the following screenshot:

Click the hamburger and you should find that the collapsible content becomes visible. Now you can be sure that the collapse plugin works as expected. The collapse plugin is also used for a responsive navbar as discussed in the next section.

Content wrapped in the .collapse is hidden by default. By clicking the toggle button, the plugin adds the  .in class which sets the display to visible. The plugin starts with adding a temporary .collapsing class which sets a CSS animation that ensures the transition goes ahead smoothly.

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 as follows; the extra small (xs) range for portrait phones with a viewport smaller than 544 pixels, the small (sm) range for landscape phones with viewports smaller than 768pixels, the medium (md) range for tablets with viewports smaller than 992pixels, the large (lg) range for desktop with viewports wider than 992pixels, and finally the extra large (xl) range for desktops with a viewport wider than 1200 pixels. The break points 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 em values should be preferred.

Note

To learn more about this, have a look at the following link: http://zellwk.com/blog/media-query-units/.

Those who still prefer em values over pixel values can simply change the $grid-breakpoints variable declaration in the scss/includes/_variables.scss file. To use em values for media queries, the SCSS code should look like the following:

$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 
); 

Notice 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 updating Bootstrap.

Responsive utility classes

Bootstrap contains some predefined utility classes for faster mobile-friendly development. You can use these classes to show or hide content by device and viewport via media query.

The .hidden-*-up classes, where the asterisks can be replaced with one of the breakpoint shorthand names, hide everything for viewports wider than the given breakpoint. So for instance, the .hidden-md-up class hides an element on medium, large, and extra-large viewports. On the other hand, the .hidden-md-down classes go in the other direction and hide an element when the viewport is smaller than the breakpoint.

Bootstrap's media query ranges, or breakpoints are also available via Sass mixins. The media-breakpoint-up() mixin with one of the breakpoint shorthands as an input parameter sets the min-width value of the media query to hide content for viewports wider than the breakpoint. The max-width of the media query to hide everything for viewports smaller than the breakpoint can be set with the media-breakpoint-down() mixin.

Consider the following SCSS, which can be written down at the end of the  scss/app.scss file:

p {  
font-size: 1.2em;
   @include media-breakpoint-up(md) {
     font-size: 1em;
   }
} 
 
The preceding SCSS code compiles into static CSS code as follows: 
p { 
  font-size: 1.2em; 
} 
 
@media (min-width: 768px) { 
  p { 
    font-size: 1em; 
} 

Completing the responsive navbar

To completely make our navbar take advantage of Bootstrap's responsive navbar solution, we need to add two new elements, with appropriate classes and data attributes.

We'll begin by adding the toggle button to the navbar code we have used before. The HTML code of your button should look like the following:

 <button class="navbar-toggler hidden-md-up pull-xs-right" type="button" data-toggle="collapse" data-target="#collapsiblecontent"> 
    ☰ 
  </button> 

As you can see in the preceding HTML code, the button has the same data attributes as before, from the collapsible content example, since the responsive navbar uses the collapse plugin too. The button has a .hidden-md-up utility class, as described before, to hide the button for viewports wider than 768px. The .pull-xs-right class ensures that the button floats on the right side of the navbar.

Secondly, you have to add the classes of the element which should collapse. We collapse the <ul> that holds the navigation links. Add the .navbar-toggleable-sm that ensures that the elements do not collapse on viewports larger than the breakpoint, while the .collapse class hides the element by default. Finally, set the unique ID specified on the data-target attribute of the button before. Your HTML code should look like the following now:

 <ul class="nav navbar-nav navbar-toggleable-sm collapse" id="collapsiblecontent"></ul> 

The complete HTML code of your responsive navbar should look as follows. You can add it to the html/pages/index.html file to test it in your browser:

<header role="banner"> 
  <nav class="navbar navbar-light bg-faded" role="navigation"> 
  <a class="navbar-brand" href="index.html">Navbar</a> 
   <button class="navbar-toggler hidden-md-up pull-xs-right" type="button" data-toggle="collapse" data-target="#collapsiblecontent"> 
    ☰ 
  </button> 
  <ul class="nav navbar-nav navbar-toggleable-sm collapse" id="collapsiblecontent"> 
    <li class="nav-item"> 
      <a class="nav-link active" href="#">Home <span class="sr-only">(current)</span></a> 
    </li> 
    <li class="nav-item"> 
      <a class="nav-link" href="#">Features</a> 
    </li> 
    <li class="nav-item"> 
      <a class="nav-link" href="#">Pricing</a> 
    </li> 
    <li class="nav-item"> 
      <a class="nav-link" href="#">About</a> 
    </li> 
  </ul> 
  </nav> 
</header> 

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.

The .navbar-brand and .nav-link classes have a float:left set by default. So that your navigation links should not float for the collapsed version of your navbar, you should undo the float. You can use the following SCSS code to remove the float for smaller viewports, and write it down at the end of the scss/app.sccs file:

.navbar { 
  @include media-breakpoint-down(sm) { 
    .navbar-brand, 
    .nav-item { 
      float: none; 
    } 
  } 
} 

If you run the bootstrap watch command your browser should automatically reload after saving the HTML or Sass code, if not, run the command again. Your browser should show the results at http://localhost:8080/. Click on and drag the edge of the browser window to make the window narrower than 768 pixels.

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!

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 available too. Consider the styling of a button in the following HTML code:

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

Now your button will look like that shown in the preceding screenshot:

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

Note

Partial attribute selectors in CSS give us the ability to make partial matches to attribute values. You can, for instance, match all elements having a class starting with btn-, so you may wonder why Bootstrap does not use the [class^='btn-'] attribute selector instead of the .btn class to set the general button styles. Firstly, Bootstrap avoids partial attribute selectors, since some people claimed these selectors are slow. Secondly, [class^='btn-']does not match "not btn-".

You can also use these classes to style a hyperlink (<a>) like a button as follows:

<a class="btn btn-primary" href="#" role="button">Link</a>

Sass variables and mixins

You can change Bootstrap's default styles by changing the Sass variables in the scss/_variabels.scss file. Setting the $brand-primary variable to a different color value will change the look of the buttons with the btn-primary class in the preceding example.

You can reuse Bootstrap's Sass mixins to extend Bootstrap with your own custom classes. Sass mixins and variables are available to build your own (semantic) grid, but you can also create a custom button class by using the following SCSS code:

.btn-tomato {
   @include button-variant(white, tomato, white);
}

The preceding SCSS code compiles into the CSS code like the following:

.btn-tomato {
   color: white;
   background-color: tomato;
   border-color: white;
}
.btn-tomato:hover {
   color: white;
   background-color: #ff3814;
   border-color: #e0e0e0;
}
.btn-tomato:focus, .btn-tomato.focus {
   color: white;
   background-color: #ff3814;
   border-color: #e0e0e0;
}
.btn-tomato:active, .btn-tomato.active,
.open > .btn-tomato.dropdown-toggle {
   color: white;
   background-color: #ff3814;
   border-color: #e0e0e0;
   background-image: none;
}
.btn-tomato:active:hover, .btn-tomato:active:focus, .btn-tomato:active.focus, .btn-tomato.active:hover, .btn-tomato.active:focus, .btn-tomato.active.focus,
   .open > .btn-tomato.dropdown-toggle:hover,
   .open > .btn-tomato.dropdown-toggle:focus,
   .open > .btn-tomato.dropdown-toggle.focus {
   color: white;
   background-color: #ef2400;
   border-color: #bfbfbf;
}
.btn-tomato.disabled:focus, .btn-tomato.disabled.focus, .btn-tomato:disabled:focus, .btn-tomato:disabled.focus {
   background-color: tomato;
   border-color: white;
}
.btn-tomato.disabled:hover, .btn-tomato:disabled:hover {
   background-color: tomato;
   border-color: white;
}

Bootstrap's Sass code avoids element and nested selectors; a motivation can be found at http://markdotto.com/2015/07/20/css-nesting/.

Bootstrap itself also avoids the @extend feature of Sass. The risk of using the @extend feature is creating complex unused CSS code. See also Hugo Giraudel's article at https://www.sitepoint.com/avoid-sass-extend/.

Using selector placeholders may reduce this risk, however Bootstrap does not use placeholder selectors. This does not forbid you from customizing and extending Bootstrap by using the @extend feature. You can, for instance, use the @extend feature to make your images responsive by default.

Images are not responsive by default in Bootstrap. To make an image responsive, you'll have to add the .img-fluid class to your <img> element.

You can use the @extend feature to make your images responsive by default by adding the following SCSS code at the end of the scss/app.scss file:

img {
   @extend .img-fluid;
}

Those who think using mixins is better than the @extend feature, should realize that Bootstrap's Sass code does not contain a mixin for making fluid images at all.

 

Browser support


As mentioned before, Bootstrap 4 does not support Internet Explorer version 8 and earlier. For projects that should support this browser I recommend you to use Bootstrap 3 instead. Bootstrap 4 also comes with optional Flexbox support. Only Internet explorer versions 11 and higher support the CSS3 Flexible Box Layout Module. You can read more about the pros and cons of the Flexbox module later on, in the Flexible Boxes section of this chapter. Besides Internet Explorer 8 and earlier, Bootstrap supports all major browsers, including many mobile browsers.

Vendor prefixes

CSS3 introduced vendor-specific rules, which offer you the possibility of writing some additional CSS, applicable for only one browser. At first sight, this seems the exact opposite of what we want. What we want is a set of standards and practicalities that work the same with every browser and a standard set of HTML and CSS which has the same effect and interpretation for every browser. These vendor-specific rules are intended to help us reach this utopia. Vendor-specific rules also provide us with early implementations of standard properties and alternative syntax. Last but not least, these rules allow browsers to implement proprietary CSS properties that would otherwise have no working standard (and may never actually become the standard).

For these reasons, vendor-specific rules play an important role in many new features of CSS3. For example, animation properties, border-radius, and box-shadow: all did depend on vendor-specific rules in past years. You can easily see that some properties may evolve from vendor prefixes to standard, because currently, most browsers support the border-radius, and box-shadow properties without any prefix.

Vendors use the following prefixes:

  • WebKit: -webkit

  • Firefox: -moz

  • Opera: -o

  • Internet Explorer: -ms

Consider the following CSS code:

transition: all .2s ease-in-out; 

For full browser support, or to support at least the browser supported by Bootstrap, we'll have to write:

  -webkit-transition: all .2s ease-in-out; 
  -o-transition: all .2s ease-in-out; 
  transition: all .2s ease-in-out; 

More information about the transition property and browser support can also be found at the following URL: http://caniuse.com/#feat=css-transitions.

Because of different browsers and their different versions, browsers may use different vendor prefixes to support the same property in writing cross-browser CSS code which can become very complex.

Bootstrap's Sass code, which compiles into CSS code does not contain any prefixes. Instead of using prefixes, the PostCSS autoprefixer has been integrated into Bootstrap's build process. When you create your own build process you should also use the PostCSS autoprefixer. In Chapter 2, Creating Your Own Build Process with Gulp, you can read how to set up a build chain with Gulp.

Flexible boxes

Bootstrap 4 also comes with optional Flexbox support. The Flexbox Layout (also called flexible boxes) is a new feature of CSS3. It is extremely useful in creating responsive and flexible layouts. Flexbox provides the ability to dynamically change the layout for different screen resolutions. It does not use floats and contains margins that do not collapse with their content. The latest versions of all major browsers now support Flexbox layouts.

Note

Information about browser support can also be found at http://caniuse.com/#feat=flexbox. Unfortunately, many older browsers do not have support for Flexbox layouts.

To enable Flexbox support, you will have to set the $enable-flex Sass variable to true and recompile Bootstrap. You do not have to change your HTML code after enabling Flexbox support.

 

The Yeoman workflow


Yeoman helps you to kickstart new projects, and you can use it as an alternative for Bootstrap CLI.

The Yeoman workflow comprises three types of tools for improving your productivity and satisfaction when building a web app: the scaffolding tool (yo), the build tool (Grunt, Gulp, and so on), and the package manager (like Bower and npm).

A Yeoman generator that scaffolds out a front-end Bootstrap 4 web app is available at https://github.com/bassjobsen/generator-bootstrap4. You can install it after installing Yeoman by running the following commands in your console:

  • Install: npm install -g generator-bootstrap4

  • Run: yo bootstrap4

  • Run grunt for building and grunt serve for preview

The Yeoman generator for Bootstrap enables you to install your code with flexbox support. The generator can also install the Font Awesome and / or the Octicons icons fonts for direct usage in your app:

 

Troubleshooting


If things are not running smoothly, you should ask yourself the following questions:

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

You might find it helpful to do the following:

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

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

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

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

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

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

Bootply is a playground for Bootstrap, CSS, JavaScript, and jQuery; you can use it to test your HTML code. You can also add your compiled CSS code, but Bootply cannot compile your CSS code.

Note

Bootply can be found online at http://www.bootply.com/.

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. You have learned the basics of a new Bootstrap 4 project. You can easily set up a new project with Bootstrap CLI now and build a responsive navbar (navigation). The navbar uses the JavaScript Collapse plugin. You understand how to compile Bootstrap's Sass code into CSS now and finally got a better understanding of Bootstrap CSS and HTML code, including browser support.

Note

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

In the next chapter, you will learn how to set up your own build process with Gulp and automatically compile your projects.

About the Authors
  • Ian Whitney

    https://coderwall.com/p/te-d2g

    Browse publications by this author
  • David Cochran

    David Cochran serves as an associate professor of communication at Oklahoma Wesleyan University. He has been teaching interactive design since 2005. When Twitter Bootstrap was first released in August 2011, he recognized it as a tool that would speed up development while supporting best practices. Thus, he began folding Bootstrap into his university courses, much to the benefit of his students.

    Browse publications by this author
Latest Reviews (17 reviews total)
I haven't had a chance to start reading either of my ebooks yet because I am finishing up a course on Javascript here and working on a Java masterclass elsewhere.
아주 좋은 자료와 지식을 받아볼수 있음, 값이 저렴하나 종이로 인쇄하니 값이 조금 비싸짐
never received item after six weeks. No local customer service number , address appeared to be in England
Bootstrap 4 Site Blueprints - Second Edition
Unlock this book and the full library FREE for 7 days
Start now