Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Mastering Bootstrap 4
Mastering Bootstrap 4

Mastering Bootstrap 4: Master the latest version of Bootstrap 4 to build highly customized responsive web apps , Second Edition

eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Mastering Bootstrap 4

Revving Up Bootstrap

Bootstrap is a web development framework that helps developers build web interfaces. Originally conceived at Twitter in 2011 by Mark Otto and Jacob Thornton, the framework is now open source and has grown to be one of the most popular web development frameworks in existence. Being freely available for private, educational, and commercial use meant that Bootstrap quickly grew in popularity. Today, thousands of organizations rely on Bootstrap, including NASA, Walmart, and Bloomberg. According to BuiltWith.com, over 10% of the world's top 1 million websites are built using Bootstrap (http://trends.builtwith.com/docinfo/Twitter-Bootstrap). As such, knowing how to use Bootstrap will be an important skill and will serve as a powerful addition to any web developer's tool belt.

The framework itself consists of a mixture of JavaScript and CSS, and provides developers with all the essential components required to develop a fully-functioning web user interface. Over the course of this book, we will be introducing you to all the most essential features that Bootstrap has to offer by teaching you how to use the framework to build a complete website from scratch. As CSS, HTML, and JavaScript alone are already the subjects of entire books in themselves, we assume that you, the reader, have at least a basic knowledge of these languages.

We begin this chapter by introducing you to our demo website, MyPhoto. This website will accompany us throughout this book, and serve as a practical point of reference. Therefore, all lessons learned will be taught within the context of MyPhoto.

We will then discuss the Bootstrap framework, listing its features and contrasting the current release to the last major release (Bootstrap 3).

Last but not least, this chapter will help you set up your development environment. To ensure equal footing, we will guide you toward installing the right build tools, and precisely detail the various ways in which you can integrate Bootstrap into a project. More advanced readers may safely skip this last part and continue to Chapter 2, Making a Style Statement.

To summarize, this chapter will do the following:

  • Introduce you to our fictional demo project—a website for photographers
  • Explain what is new in the latest version of Bootstrap, and how the latest version differs from the previous major release
  • Show you how to include Bootstrap in our web project

Introducing our demo project

This book will teach you how to build a complete Bootstrap website from scratch. Starting with a simple layout in Chapter 2, Making a Style Statement, and Chapter 3, Building the Layout, we will build and improve the website's various sections as we progress through each chapter. The concept behind our website is simple—to develop a landing page for photographers. Using this landing page, (hypothetical) users will be able to exhibit their wares and services. While building our website, we will be making use of the same third-party tools and libraries that you would if you were working as a professional software developer. We chose these tools and plugins specifically because of their widespread use. Learning how to use and integrate them will save you a lot of work when developing websites in the future. The tools that we will use to assist us throughout the development of MyPhoto are node package manager (npm) and grunt.

From a development perspective, the construction of MyPhoto will teach you how to use and apply all the essential user interface concepts and components required to build a fully-functioning website. Among other things, you will learn how to do the following:

  • Using the Bootstrap grid system to structure the information presented on your website.
  • Creating a fixed, branded navigation bar with animated scroll effects.
  • Using an image carousel for displaying different photographs, implemented using Bootstrap's carousel and jumbotron (jumbotron is a design principle for displaying important content). It should be noted that carousels are becoming an increasingly unpopular design choice; however, they are still heavily used and are an important feature of Bootstrap. As such, we do not argue for or against the use of carousels, as their effectiveness depends very much on how they are used, rather than on whether they are used.
  • Building custom tabs that allow users to navigate through different contents.
  • Using and applying Bootstrap's modal dialogs.
  • Applying a fixed page footer.
  • Creating forms for data entry using Bootstrap's input controls (text fields, text areas, and buttons) and applying Bootstrap's input validation styles.
  • Making the best use of Bootstrap's context classes.
  • Creating alert messages and learning how to customize them.
  • Rapidly developing interactive data tables for displaying product information.
  • Using drop-down menus, custom fonts, and icons.
  • Creating breadcrumbs to aid navigation.
  • Learning to use typeahead.
  • Effectively using Bootstrap utility classes to speed up website development.
  • Managing alignment and layout using flexbox.
  • Building interfaces that support screen readers.

In addition to learning how to use Bootstrap 4, the development of MyPhoto will introduce you to a range of third-party libraries such as Scrollspy (for scroll animations), SalvattoreJS (a library for complementing our Bootstrap grid), Animate.css (for beautiful CSS animations, such as fade-in effects), and Bootstrap DataTables (for rapidly displaying data in tabular form).

The website itself will consist of different sections:

  • A Welcome section
  • An About section
  • A Services section
  • A Gallery section
  • A Contact Us section

The development of each section is intended to teach you how to use a distinct set of features found in third-party libraries. For example, by developing the Welcome section, you will learn how to use Bootstrap's jumbotron and alert dialogs along with different font and text styles, while the About section will show you how to use cards. The Services section of our project introduces you to Bootstrap's custom tabs—that is, you will learn how to use Bootstrap's tabs to display a range of different services offered by our website.

Following on from the Services section, you will need to use rich imagery to really show off the website's sample services. You will achieve this by mastering Bootstrap's responsive core along with Bootstrap's carousel and third-party jQuery plugins. Last but not least, the Contact Us section will demonstrate how to use Bootstrap's form elements and helper functionsthat is, you will learn how to use Bootstrap to create stylish HTML forms, how to use form fields and input groups, and how to handle the display of data validation results.

Finally, toward the end of the book, you will learn how to optimize your website, and integrate it with the popular JavaScript frameworks, AngularJS (https://angularjs.org/) and React (https://reactjs.org/). As entire books have been written on AngularJS alone, we will only cover the essentials required for the integration itself.

Now that you have glimpsed a brief overview of MyPhoto, let's examine Bootstrap 4 in more detail and discuss what makes it so different from its predecessor. Take a look at the following screenshot:

Figure 1.1: A taste of what is to come: the MyPhoto landing page

What Bootstrap 4 has to offer

Much has changed since Twitter's Bootstrap was first released on August 19th, 2011. In essence, the first version of Bootstrap was a collection of CSS rules offering developers the ability to lay out their website, create forms, buttons, and help with general appearance and site navigation. With respect to these core features, Bootstrap 4 is still much the same as its predecessors—that is, how one uses the framework to create layouts and user interfaces with a consistent appearance. The latter is achieved by applying Bootstrap styles to buttons, forms, and other user interface elements.

While the elementary features of Bootstrap have remained the same, under the hood, the framework has changed completely, as Bootstrap 4 has been rewritten from scratch. As such, the framework introduces new utility classes and new components, and drops support for others at the same time. The appearance of individual components has changed too, and so has the manner in which third-party plugins should be defined and created. The developers of Bootstrap 4 have also stopped support for some older web-browsers and added support for others - namely, Android v5.0 Lollipop’s Browser and WebView. Along with Bootstrap's major features, we will be discussing these changes in the subsections that follow.

Layout

Possibly the most important and widely used feature is Bootstrap's ability to lay out and organize a page. At the core of this functionality lies the Bootstrap grid system: a series of CSS classes and media queries that allow you to easily define the horizontal and vertical position of elements on a page, taking into account different screen sizes at the same time. Using the grid system is as easy as applying a few classes to your elements and specifying a tier (that is, the viewport size at which the sizing for the element takes effect). No JavaScript magic or custom CSS rules need to be written. With Bootstrap 4, this grid system has been completely overhauled, and a new grid tier has been added. This means that in contrast to Bootstrap 3, the grid system now offers tiers for extra-small, small, medium, large, and extra-large displays. We will be talking about tiers, breakpoints, and Bootstrap's grid system extensively in Chapter 2, Making a Style Statement.

Along with the grid system, Bootstrap offers the following:

  • Responsive containers.
  • Responsive breakpoints for adjusting page layout in response to differing screen sizes.
  • Media objects that act as building blocks and allow you to build your own structural components.
  • Utility classes that allow you to manipulate elements in a responsive manner. For example, you can use the layout utility classes to hide elements, depending on screen size.

Also, Bootstrap 4 now ships with default support for a CSS3 layout mode called flexbox, for the easier positioning of elements while also accounting for different screen sizes. We will be talking about how to manage element alignment using flexbox later on in Chapter 8, Utilities.

Content styling

As already noted, one of Bootstrap’s core objectives is to allow the development of consistent user interfaces. This means that using Bootstrap, one should be able to build web pages that look and feel the same, regardless of which browser is being used to view them. Alternatively, in other words, and as noted in the official Bootstrap 4 documentation:

"part of Bootstraps job is to provide an elegant, consistent, and simple baseline to build upon."

As different browsers ship with different element styles, Bootstrap overrides all the default browser styles, hence ensuring the consistent rendering of elements across different browsers. The overriding is achieved using a collection of Bootstrap CSS rules collectively known as Reboot. These rules are the Bootstrap team's own modification of Normalize—a third-party library (used by Bootstrap 3) for resetting default element styles.

Building on top of this clean slate, Bootstrap 4 provides a set of basic styles that allow you to effectively improve the general look and feel of the most commonly-used elements used to construct user interfaces. Examples of the elements that Bootstrap allows you to style are buttons (figure 1.2), input fields, headings (figure 1.3), paragraphs, special inline texts, figures, tables, and navigation controls.

Figure 1.2: The six button styles that come with Bootstrap 4 are btn-primary, btn-secondary, btn-success, btn-danger, btn-link, btn-info, and btn-warning. Additional button styles not shown here include btn-light, btn-dark, and outline button styles in the form of btn-outline-*.

In addition, Bootstrap offers state styles for all input controls—for example, styles for disabled buttons or toggle buttons:

Figure 1.3: Bootstrap's typography styles. In the above example, we see styling for different display headers

It should be noted that the default font size in Bootstrap 4 is now 2 px bigger than in its predecessor, having increased from 14 px to 16 px. Naturally, this makes textual content, such as body text and headings, appear slightly larger without being too obtrusive. The display of text is now also controlled by your native font stack (also known as the system font stack; the native font stack refers to the default collection of fonts used by your operating system) as opposed to the default web fonts. Using the native font stack has the following advantages:

  • Improved overall rendering speed of text as the web browser no longer needs to download any font files
  • Allows for a more consistent look and feel as a page's text content matches that of the operating system the browser is running on

Components

Bootstrap offers a large collection of fundamental user interface (UI) components that allow you to quickly construct any type of user interface. Specifically, Bootstrap offers Modal dialogs, progress bars, navigation bars, tooltips, popovers, a carousel, alerts, drop-down menus, input groups, tabs, pagination, cards, forms, list groups, breadcrumbs, and a jumbotron (refer to figure 1.4). All of these components, in addition to collapsible content—such as accordions—come out of the box and ready to use.

In addition, they can be styled using one of four context colors introduced in the previous subsection or customized to suit specific needs.

Figure 1.4: Various Bootstrap 4 components in action. In the preceding screenshot, we see a sample jumbotron, a card, some sample text, a progress bar and some buttons.

Readers familiar with Bootstrap 3 will have noted that panels, wells, and thumbnails do not feature in the preceding screenshot, figure 1.4. That is because these components have been replaced with a new concept—cards. To readers unfamiliar with the concept of wells, a well is a UI component that allows developers to highlight text content by applying an inset shadow effect to the element to which it is applied. A panel, on the other hand, also serves to highlight information, but by applying padding and rounded borders. Neither panels nor wells, however, took into account different types of contents.

Cards address this shortcoming by being less restrictive and giving the developer the flexibility to support different types of content, such as images, lists, or text, and allowing for the adding of footers and headers; look at figure 1.5:

Figure 1.5: The Bootstrap 4 card component replaces the existing wells, thumbnails, and panels

Forms in Bootstrap 4 have also been overhauled and now offered for the configuration of different layout options (refer to Figure 1.6) as well as shipping with input validation classes (check out Figure 1.7):

Figure 1.6: Bootstrap 4 forms can be configured using different layout optionsin the preceding screenshot, we see three forms: one with the label arranged above the input, one whereby the form elements are inline, and one form whereby the label is placed to the left of the input

By applying these classes, the developer can quickly indicate erroneous input or inform the user of the successful submission of the form; doing so in the past required the use of third-party libraries or a manual implementation. Individual form controls - such as buttons - can now also be adjusted in size - a feature that seems trivial, but is often widely required:

Figure 1.7: The new Bootstrap 4 input validation styles, indicating the successful processing of input.

The form controls can also be themselves customized while maintaining cross-browser consistency across input elements by applying the custom-* classes (refer to figure 1.7). In essence, these classes allow one to replace the default checkbox, radio, select and file upload input controls (check out figure 1.8, as follows) while maintaining a consistent look:

Figure 1.8: Custom Bootstrap input controls that replace the browser defaults in order to ensure cross-browser UI consistency

Mobile support

Similar to its predecessor, Bootstrap 4 allows you to create mobile-friendly websites without too much additional development work. By default, Bootstrap is designed to work across all resolutions and screen sizes, from mobile to tablet to a desktop. In fact, Bootstrap's mobile-first design philosophy implies that its components must display and function correctly at the smallest screen size possible. The reasoning behind this is simple. Think about developing a website without consideration for small mobile screens. In this case, you are likely to pack your website full of buttons, labels, and tables. You will probably only discover any usability issues when a user attempts to visit your website using a mobile device, only to find a small web page that is crowded with buttons and forms. At this stage, you will be required to rework the entire user interface to allow it to render on smaller screens. For precisely this reason, Bootstrap promotes a bottom-up approach, forcing developers to get the user interface to render correctly on the smallest possible screen size, before expanding upward.

Utility classes

Apart from ready-to-go components, Bootstrap offers a large selection of utility classes that encapsulate the most commonly needed functionality in order to reduce the number of repetitive style rules. Examples of such utilities include classes for quickly styling borders, clearing floats, creating generic close icons, defining colors, changing the display and visibility properties of elements, and adjusting size and spacing. Some of these utility classes already existed in Bootstrap 3, while others are brand new or have been adapted, renamed, or modified. We will be using these utility classes throughout the course of this book, and they will gain our full, undivided attention in Chapter 8, Utilities, for example, rules for aligning text, hiding an element, or providing contextual colors for warning text.

Supported browsers

Bootstrap 4 supports the latest stable release of all modern browsers on both desktop and mobile devices, that is, Firefox, Chrome, Opera, Safari, Internet Explorer 10 - 11, and Microsoft Edge. Furthermore:

“Alternative browsers which use the latest version of WebKit, Blink, or Gecko, whether directly or via the platform’s web view API, are not explicitly supported. However, Bootstrap should (in most cases) display and function correctly in these browsers as well. More specific support information is provided below.”

                                                                         (source: official Bootstrap 4 documentation)

It is important to note that unlike its predecessor, Bootstrap 4 no longer supports Internet Explorer 9 and earlier versions. The decision to only support newer versions of Internet Explorer was a reasonable one, as Microsoft itself doesn't provide technical support and updates for Internet Explorer 8 (and earlier versions) anymore (as of January 2016). Furthermore, as we will discover later on in this book, Bootstrap 4 relies on flexbox, which is also not supported by older browsers.

Furthermore, Internet Explorer 8 (and earlier) does not support rem, meaning that Bootstrap 4 would have been required to provide a workaround. This, in turn, would most likely have implied a large amount of additional development work, with the potential for inconsistencies. Lastly, responsive website development for Internet Explorer 8 (and earlier) is difficult, as the browser does not support CSS media queries. Given these three factors, dropping support for this version of Internet Explorer was the most sensible path of action.

Sass instead of Less

Both Less and Sass (Syntactically Awesome Stylesheets) are CSS extension languages—that is, they are languages that extend the CSS vocabulary with the objective of making the development of many, large, and complex stylesheets easier. Although Less and Sass are fundamentally different languages, the general manner in which they extend CSS is the same—both rely on a preprocessor. As you produce your build, the preprocessor is run, parsing the Less/Sass script and turning your Less or Sass instructions into plain CSS.

Less is the official Bootstrap 3 build, while Bootstrap 4 has been developed from scratch, and is written entirely in Sass. Both Less and Sass are compiled into CSS to produce bootstrap.css. Along with that, it also produces its minified version—bootstrap.min.cssand map files. It is this CSS file that we will be primarily referencing throughout this book (with the exception of Chapter 3, Building the Layout). Consequently, you will not be required to know Sass in order to follow this book. However, we do recommend that you take a 20-minute introductory course on Sass if you are completely new to the language. Rest assured if you already know CSS; you will not need more time than this. The language's syntax is very close to normal CSS, and its elementary concepts are similar to those contained within any other programming language.

From pixel to root em

Unlike its predecessor, Bootstrap 4 no longer uses pixel (px) as its unit of typographic measurement. Instead, it primarily uses root em (rem). The reasoning behind choosing rem is based on a well-known problem with px; websites using px may render incorrectly, or not as originally intended, as users change the size of the browser's base font. Using a unit of measurement that is relative to the page's root element helps address this problem, as the root element will be scaled relative to the browser's base font. In turn, a page will be scaled relative to this root element.

Typographic units of measurement

Simply put, typographic units of measurement determine the size of your font and elements. The most commonly used units of measurement are px and em. The former is an abbreviation for pixel and uses a reference pixel to determine a font's exact size. This means that for displays of 96 dots per inch (dpi), 1 px will equal an actual pixel on the screen. For higher resolution displays, the reference pixel will result in the px being scaled to match the display's resolution. For example, specifying a font size of 100 px will mean that the font is exactly 100 pixels in size (on a display with 96 dpi), irrespective of any other element on the page.

EM is a unit of measurement that is relative to the parent of the element to which it is applied. So, for example, if we were to have two nested div elements, the outer element with a font size of 100 px and the inner element with a font size of 2 em, then the inner element's font size would translate to 200 px (as in this case 1 em = 100 px). The problem with using a unit of measurement that is relative to parent elements is that it increases your code's complexity, as the nesting of elements makes size calculations more difficult.

The recently introduced rem measurement aims to address both em's and px's shortcomings by combining their two strengths; instead of being relative to a parent element, rem is relative to the page's root element.

Vendor prefix mixing

Since Bootstrap 4 relies on a tool called Autoprefixer to automatically add vendor prefixes to CSS rules, the vendor prefix mixins which were marked as deprecated in Bootstrap version 3.2 have now been completely removed. In addition, the following mixins have also been removed (source: Bootstrap 4 documentation—https://getbootstrap.com/docs/4.0/migration/):

animation, animation-delay, animation-direction, animation-duration, animation-fill-mode, animation-iteration-count, animation-name, animation-timing-function, backface-visibility, box-sizing, content-columns, hyphens, opacity, perspective, perspective-origin, rotate, rotateX, rotateY, scale, scaleX, scaleY, skew, transform-origin, transition-delay, transition-duration, transition-property, transition-timing-function, transition-transform, translate, translate3d, and user-select

Icons

Bootstrap 3 shipped with Glyphicons—a nice collection of over 250 font icons, free of use. While great in theory, font icons come with a number of problems in practice:

  • Font icons may break screenreaders as the readers will literally try to read out the icon.
  • Persons with fonts to aid their reading. Font icons will break if that happens.
  • If the icons fail, then the web browser replaces them with a default fallback. This makes controls using these icons look funny at best.

These three major problems, combined with the desire to make Bootstrap 4 more lightweight, led to the development team’s decision to no longer make Glyphicons available (however, this does not prevent one from including font icon set manually).

Themes

Bootstrap 4 offers a collection of premium themes. At the time of writing, the Bootstrap team offered three distinct themes:

  • A Dashboard theme containing premium components aimed toward admin and analytic websites
  • A Marketing theme for generic e-commerce and marketing websites
  • An Application theme containing components and utilities for building generic web applications (refer to figure 1.9)

Each theme works seamlessly with Bootstrap 4 and ships with all assets included. A multiuse license for these themes costs $99, while an extended license that allows for redistribution and resale costs $999.

Figure 1.9: The premium Bootstrap 4 “Application” theme as shown on the official Bootstrap website - https://themes.getbootstrap.com/

Customization

The developers behind Bootstrap 4 have put specific emphasis on customization throughout the development of Bootstrap 4. As such, many new variables have been introduced that allow for the easy customization of Bootstrap. Using the $enabled-*- Sass variables (found in node_modules/bootstrap/scss/_variables.scss), one can now enable or disable specific global CSS preferences.

Setting up our project

Now that we know what Bootstrap has to offer, let's set up our project:

  1. Create a new project directory named MyPhoto. This will become our project root directory.
  2. Create a blank index.html file and insert the following HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<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">
<title>MyPhoto</title>
</head>
<body>
<div class="alert alert-success"> Hello World!
</div>
</body>
</html>

Note the three meta tags. The first tag tells the browser that the document in question is utf-8 encoded. Since Bootstrap optimizes its content for mobile devices, the subsequent meta tag is required to help with viewport scaling. The last meta tag forces the document to be rendered using the latest document rendering mode available if viewed in Internet Explorer.

  1. Open index.html in your browser. You should see just a blank page with the words Hello World.

Now it is time to include Bootstrap. At its core, Bootstrap is a glorified CSS style sheet. Within that style sheet, Bootstrap exposes very powerful features of CSS with an easy-to-use syntax. It being a style sheet, you include it in your project as you would with any other style sheet that you might develop yourself—that is, open the index.html and directly link it to the style sheet.

Viewport scaling

The term "viewport" refers to the available display size to render the contents of a page. The viewport meta tag allows you to define this available size. Viewport scaling using meta tags was first introduced by Apple and, at the time of writing, is supported by all major browsers.

Using the width parameter, we can define the exact width of the user's viewport. For example, <meta name="viewport" content="width=320"> will instruct the browser to set the viewport's width to 320px. The ability to control the viewport's width is useful when developing mobile-friendly websites; by default, mobile browsers will attempt to fit the entire page onto their viewports by zooming out as far as possible. This allows users to view and interact with websites that have not been designed to be viewed on mobile devices. However, as Bootstrap embraces a mobile-first design philosophy, a zoom out will, in fact, result in undesired side effects. For example, breakpoints (which we will discuss in Chapter 2, Making a Style Statement) will no longer work as intended, as they now deal with the zoomed-out equivalent of the page in question. This is why explicitly setting the viewport width is so important. By writing content="width=device-width, initial-scale=1, shrink-to-fit=no", we are telling the browser the following:
  • We want to set the viewport's width to be equal to the actual device's screen width
  • We do not want any zoom initially
  • We do not wish to shrink the content to fit the viewport

For now, we will use the Bootstrap builds hosted on Bootstrap's official Content Delivery Network (CDN). This is done by including the following HTML tag into the head of your HTML document (the head of your HTML document refers to the contents between the <head> opening tag and the </head> closing tag):

<link rel="stylesheet" 
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" >

Bootstrap relies on jQuery, a JavaScript framework that provides a layer of abstraction in an effort to simplify the most common JavaScript operations (such as element selection and event handling). If you just need Bootstrap for laying out your app, you don't need to include those JS files. The Bootstrap JavaScript files are only needed if you'll use any of these components:

  • Alerts
  • Buttons
  • Carousels
  • Collapsible content
  • Dropdowns
  • Navbar
  • Tooltips
  • Scrollspy

Since we will be making use of all the aforementioned components, we must include the Bootstrap JavaScript file, and we must first include jQuery. Both inclusions should occur just before the </body> closing tag.

Let's add the following to our HTML document:

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

Note that while these scripts could, of course, be loaded at the top of the page, loading scripts at the end of the document is considered the best practice to speed up page loading time and to avoid JavaScript issues preventing the page from being rendered. The reason for this is that browsers do not download all dependencies in parallel (although a certain number of requests are made asynchronously, depending on the browser and the domain). Consequently, forcing the browser to download dependencies early on will block page rendering until these assets have been downloaded. Furthermore, ensuring that your scripts are loaded last will ensure that once you invoke Document Object Model (DOM) operations in your scripts, you can be sure that your page's elements have already been rendered. As a result, you can avoid checks that ensure the existence of given elements.

What is a Content Delivery Network?

The objective behind any Content Delivery Network (CDN) is to provide users with content that is highly available. This means that a CDN aims to provide you with content, without this content ever (or rarely) becoming unavailable. To this end, the content is often hosted using a large, distributed set of servers. The BootstrapCDN basically allows you to link to the Bootstrap stylesheet so that you do not have to host it yourself.

Save your changes and reload the index.html in your browser. The Hello World string should now contain a green background:

Figure 1.10: Our “Hello World” styled using Bootstrap 4

Now that the Bootstrap framework has been included in our project, open your browser's developer console (if using Chrome on Microsoft Windows, press Ctrl + Shift + I; on macOS X, you can press cmd + Alt + I). As Bootstrap requires another third-party library Popper, for displaying popovers and tooltips, the developer console will display an error (Figure 1.6). Take a look at the following screenshot:

Figure 1.11: Chrome's Developer Tools can be opened by navigating to View, selecting Developer, and then clicking on Developer Tools. At the bottom of the page, a new view will appear. Under the Console tab, an error will indicate an unmet dependency

Popper is available via the CloudFare CDN and consists of both a CSS file and a JavaScript file. The dependency is a library that allows for the easy positioning of tooltips and popovers and is approximately 6 KB in size. It should be noted that the required version for Bootstrap is 1.12.9, although Bootstrap will function correctly—except for its tooltips and popoversif the library, or an incorrect version of the library, is being included:

<!DOCTYPE html>
<html lang="en">
<head>
<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">
<title>MyPhoto</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/
bootstrap/4.0.0/css/bootstrap.min.css" >
</head>
<body>
<div class="alert alert-success">
Hello World!
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/
1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/
bootstrap.min.js"></script>
</body>
</html>

While CDNs are an important resource, there are several reasons why, at times, using a third-party CDN may not be desirable:

  • CDNs introduce an additional point of failure, as you now rely on third-party servers.
  • The privacy and security of users may be compromised, as there is no guarantee that the CDN provider does not inject malicious code into the libraries that are being hosted, nor can one be certain that the CDN does not attempt to track its users.
  • Certain CDNs may be blocked by the Internet Service Providers of users in different geographical locations.
  • Offline development will not be possible when relying on a remote CDN.
  • You will not be able to optimize the files hosted by your CDN. This loss of control may affect your website's performance (although typically, you are more often than not offered an optimized version of the library through the CDN).

Instead of relying on a CDN, we can manually download the jQuery, Popper, and Bootstrap project files. We can then copy these builds into our project root and link them to the distribution files. The disadvantage of this approach is the fact that maintaining a manual collection of dependencies can quickly become very cumbersome and next to impossible as your website grows in size and complexity.

As such, we will not manually download the Bootstrap build. Instead, we will let NPM do it for us. NPM is a package management system—that is, a tool that you can use to manage your website's dependencies. It automatically downloads, organizes, and (upon command) updates your website's dependencies. To install Bower, head over to https://www.npmjs.com/get-npm.

Once NPM has been installed, open up your terminal, navigate to the project root folder you created earlier, and fetch the Bootstrap build:

npm init
npm install bootstrap

This will create a new folder structure in our project root:

|  node_modules
| bootstrap
| LICENSE
| README.md
| package.json
| dist
| js
| scss

We will explain all of these various files and directories later on in this book. For now, you can safely ignore everything except for the dist directory inside node_modules/bootstrap/. Go ahead and open the dist directory. You should see three subdirectories:

  • css
  • js

The name dist stands for distribution. Typically, the distribution directory contains the production-ready code that users can deploy. As its name implies, the css directory inside dist includes the ready-for-use style sheets. Likewise, the js directory contains the JavaScript files that compose Bootstrap.

To reference the local Bootstrap CSS file in our index.html, modify the href attribute of the link tag that points to bootstrap.min.css:

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

Let's do the same for the Bootstrap JavaScript file:

<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

Repeat this process for both jQuery and Popper. To install jQuery using Bower, use the following command:

npm install jquery@>=3.0.0

Just as before, a new directory will be created inside the node_modules directory:

|  node_modules
| jquery
| AUTHORS.txt
| LICENSE.txt
| README.md
| bower.json
| dist
| external
| package.json
| src

Again, we are only interested in the contents of the dist directory, which, among other files, will contain the compressed jQuery build jquery.min.js.

Reference this file by modifying the src attribute of the script tag that currently points to Google's jquery.min.js by replacing the URL with the path to our local copy of jQuery:

<script src="node_modules/jquery/dist/jquery.min.js"></script>

Last but not least, repeat the steps already outlined for Popper:

npm install popper.js@^1.12.9

Once the installation completes, a similar folder structure to the ones for Bootstrap and jQuery will have been created. Verify the contents of node_modules/popper.js/dist and replace the CDN Popper references in our index.html with their local equivalent. The final index.html should now look as follows:

<!DOCTYPE html>
<html lang="en">
<head>
<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">
<title>MyPhoto</title>
<link rel="stylesheet"
href="node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<div class="alert alert-success">
Hello World!
</div>
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/popper.js/dist/umd/popper.min.js">
</script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js">
</script>
</body>
</html>

Refresh the index.html in your browser to ensure that everything works.

What IDE and browser should I be using when following the examples in this book? 
While we recommend a JetBrains IDE or Sublime Text along with Google Chrome, you are free to use whatever tools and browser you like. Our taste in IDE and browser is subjective in this matter. However, keep in mind that Bootstrap 4 does not support Internet Explorer 9 or earlier versions. As such, if you do happen to use Internet Explorer 9, you should upgrade it to the latest version.

Summary

The goal of this chapter was to introduce you to Bootstrap 4, and explain the following things to you:

  • What Bootstrap has to offer.
  • Why you should use Bootstrap.
  • How to get started using Bootstrap. 

As such, you should now understand that Bootstrap can assist developers in building the layout of a page, structuring and styling its contents as well as how to "bootstrap" a simple HTML page.

During the wider course of this discussion, we also highlighted and explained some important concepts in web development, such as typographic units of measurement or the definition, purpose, and justification for the use of Content Delivery Networks.

Last but not least, we introduced you to our sample project—MyPhoto—which sets the scene for the remainder of the book, as we will use it to illustrate just how to use Bootstrap in order to develop a modern website.

Now, let's move on to  Chapter 2, Making a Style Statement, so that we can introduce you to the Bootstrap grid system by building a general layout for the first page of our sample project

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Master the art of creating highly intuitive and responsive web interfaces with Bootstrap 4
  • Combine the power of Bootstrap and popular front-end JavaScript frameworks such as Angular and React to build cutting-edge web apps
  • Infuse your web pages with life and movement using Bootstrap jQuery plugins

Description

Bootstrap 4 is a free CSS and JavaScript framework that allows developers to rapidly build responsive web interfaces. This book will help you use and adapt Bootstrap to produce enticing websites that fit your needs. You will build a customized Bootstrap website from scratch, using various approaches to customize the framework with increasing levels of skill. You will get to grips with Bootstrap's key features and quickly discover various ways in which Bootstrap can help you develop web interfaces. Then take a walk through the fundamental features, such as its grid system, global styles, helper classes, and responsive utilities. When you have mastered these, you will discover how to structure page layouts, utilize Bootstrap's various navigation components, use forms, and style different types of content. Among other things, you will also tour the anatomy of a Bootstrap plugin, create your own custom components, and extend Bootstrap using jQuery. You will also understand what utility classes Bootstrap 4 has to offer, and how you can use them effectively to speed up the development of your website. Finally, you will discover how to optimize your website and integrate it with third-party frameworks. By the end of this book, you will have a thorough knowledge of the framework's ins and outs, and will be able to build highly customizable and optimized web interfaces.

Who is this book for?

This book targets readers who wish to leverage Bootstrap 4 to create responsive web applications. Basic knowledge of web development concepts and web technologies such as HTML, CSS, and JavaScript is required.

What you will learn

  • •Create a professional Bootstrap-based website from scratch without using third-party templates
  • •Leverage Bootstrap s powerful grid system
  • •Style various types of content and learn how to build a page s layout from scratch by applying the power of Bootstrap 4
  • •Take advantage of Bootstrap s form helper and contextual classes
  • •Improve your website s overall user experience with headers and footers
  • •Infuse your web pages using Bootstrap jQuery plugins and create your own Bootstrap plugins
  • •Learn what utility classes Bootstrap 4 has to offer, how they are implemented, and the best way to use them.
  • •Create more advanced web interfaces by leveraging the power of accordions, dropdowns, and list groups.
  • •Incorporate Bootstrap into an AngularJS or React application and use Bootstrap components as AngularJS directives

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 22, 2018
Length: 354 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788838214
Vendor :
Bootstrap
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Feb 22, 2018
Length: 354 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788838214
Vendor :
Bootstrap
Languages :
Tools :

Packt Subscriptions

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

Frequently bought together


Stars icon
Total $ 141.97
Mastering Bootstrap 4
$48.99
Bootstrap 4 Cookbook
$48.99
Learning jQuery 3
$43.99
Total $ 141.97 Stars icon

Table of Contents

12 Chapters
Revving Up Bootstrap Chevron down icon Chevron up icon
Making a Style Statement Chevron down icon Chevron up icon
Building the Layout Chevron down icon Chevron up icon
On Navigation, Footers, Alerts, and Content Chevron down icon Chevron up icon
Speeding Up Development Using Third-Party Plugins Chevron down icon Chevron up icon
Customizing Your Plugins Chevron down icon Chevron up icon
Advanced Third-Party Plugins Chevron down icon Chevron up icon
Utilities Chevron down icon Chevron up icon
List Groups and Accordions Chevron down icon Chevron up icon
Optimizing Your Website Chevron down icon Chevron up icon
Integrating with AngularJS and React Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(6 Ratings)
5 star 33.3%
4 star 0%
3 star 16.7%
2 star 33.3%
1 star 16.7%
Filter icon Filter
Top Reviews

Filter reviews by




DefendTek.us Jul 26, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Easy to follow along, work as you go type book. I liked it - it worked for me going from BS 3 to 4.
Amazon Verified review Amazon
Fan Amazon Customer Dec 17, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
C'est le livre que j'attendais, commencé à pratiquer le projet de site web proposé par l'auteur pour enseigner Bootstrap 4. C'est une pédagogie intéressante.
Amazon Verified review Amazon
Michael May 04, 2019
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Good for someone wishing to extend their general knowledge and consolidate on concepts they may not be sure about. Building a website as a teaching tool is overused and it would have been better to use smaller 'CODEPEN' Type examples of varying complexity to explain how things work and when to use them, the book would then be worth the asking price. The most annoying feature is the way text is obscured by large black circular icons, supposedly to draw attention to important concepts. It does not work and has the opposite effect as it makes the text very difficult to read.
Amazon Verified review Amazon
William J. Gecawich Apr 06, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I was hoping for this ebook to be a searchable reference as I tried to do various tasks in Bootstrap. Unfortunately very little of the information was in the book. I found better information from the official bootstrap documentation site.
Amazon Verified review Amazon
Ben Lanning Mar 31, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I was very disappointed in this book for two reasons.First, the quality of the ebook itself was quite low. Little to no effort had been made to ensure that the layout was correct after it was converted to the kindle format and many of the code blocks and images were very difficult to take advantage of due to their low quality, being overwritten by other content, or sloppy layout.And second, the actual content of the book was extremely lacking. I am primarily a hobbyist programmer, but have successfully taught myself a number of new languages and tech stacks as I needed them for a project. As a result I rely heavily on the official documentation of any given project or language. As a result I was very disappointed to find that the content of this book was mostly fluff and that it was, in almost every case, less helpful and informative than the actual bootstrap website with regard to layout help, examples, use cases, code snippets, and even general advice on planning and designing a web page. For a book titled "Mastering Bootstrap 4" I fully expected there to be more in depth and detailed information than I can find for free on the project website in about five minutes.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.