
Dedicated to my wife, Matina
Designing your website or web application to offer great experience for the user when they are on a mobile device is a very big challenge. Not only that, you want them to enjoy the same awesome experience no matter what is the size of the display they are using.
Don’t worry! You are in good hands. Twitter Bootstrap has done the work for you. It is the CSS framework that gives you all the tools to develop an HTML page that works well on any display size—from iPhone 6 to iPhone X and to iPads and to large and extralarge displays. It has been engineered on top of the latest CSS tools and techniques, like flexbox, and works on the majority of the browsers on any device.
However, for those who haven’t worked before with any CSS framework like this, their official documentation, which works more like a reference, might be intimidating, which leads you to this book here. You are going to learn Twitter Bootstrap using practical examples, instead of reading long reference pages with API details. Hence, you are going to be productive very quickly. You will get confidence, and you will apply it to your daily work and projects much sooner than just reading the official documentation. Official documentation is excellent reference, but this book here will put you up to speed much earlier.
This book is aimed at web developers in the front-end layer of the stack. It assumes that you have a good knowledge of HTML, CSS, and JavaScript. Also, you need to know jQuery, since it is the JavaScript library Twitter Bootstrap relies on.
Chapter 1, “Getting Started”: This chapter introduces you to Twitter Bootstrap and the grid system.
Chapter 2, “Advanced Grid Techniques”: This chapter brings you in contact with some more advanced features of the Bootstrap grid.
Chapter 3, “Target Project 1”: This chapter allows you to learn about navigation bars by building your first Twitter Bootstrap project.
Chapter 4, “Theme Reference: Part 1”: In this chapter, you build a long page with various Twitter Bootstrap components, like buttons, tables, and badges.
Chapter 5, “Theme Reference: Part 2”: This is the continuation of the previous chapter, with more Bootstrap components to build in the Theme Reference project.
Chapter 6, “Cover Page Project”: In this chapter, you implement a page which has a background image as cover and content centered in the middle.
Chapter 7, “Admin Dashboard”: In this chapter, you implement an administrator dashboard with left-side navigation bar, images, and tables.
Chapter 8, “Forms”: In this chapter, you implement a page with various Twitter Bootstrap forms.
Chapter 9, “Modal Dialogs”: In this chapter, you learn how to implement modal dialogs, a very popular UX component.
Chapter 10, “ScrollSpy”: In this chapter, you learn how to follow the user and highlight the correct menu item in the navigation bar, using ScrollSpy.
Chapter 11, “Tooltips and Popovers”: Finally, you learn about tooltips and popovers, which are very useful UX components in conveying extra information to the user.
The symbol $ is used to denote an Operating System shell prompt, that is, where you should type a command that will be executed by your Operating System. For example, if you work with a Mac OS, you can open a terminal and type the command that follows this symbol.
All the code listings of this book are available for download at https://github.com/Apress/practical-bootstrap .


has a background in mechanical engineering from the University of Ibadan, Nigeria, and has been a front-end developer for over 3 years working on both web and mobile technologies. He also has experience as a technical author, writer, and reviewer. He enjoys programming for the Web, and occasionally, you can also find him playing soccer. He was born in Benin City and is currently based in Lagos, Nigeria.
Creating responsive websites and applications is becoming a hard requirement now that many people have started using mobile phones and tablets. Twitter Bootstrap is here to give you all the necessary tools, so that the work you create is equally well viewed on various display sizes.
This chapter starts with the basics of Twitter Bootstrap, mainly its grid system.

A Demo Page That Shows the Twitter Bootstrap Grid System

Page as Viewed on Large Displays

Page Adapts Its Layout on Smaller Devices
Learn what Twitter Bootstrap is.
Learn how to include Twitter Bootstrap CSS and JavaScript libraries in your project.
Learn about the two main containers available and their differences.
Learn about how the grid system of Twitter Bootstrap can help you organize the content of your page and generate a responsive layout.
Twitter Bootstrap is a set of CSS and JavaScript code that you can base your own HTML, CSS, and JavaScript code on, in order to quickly have a website or web application that is responsive, with a mobile-first design approach.
In other words, it provides you with some CSS classes and JavaScript code that you can just go and use. You apply the classes, and you use the JavaScript modules and quickly have your website and your web application have features that would have taken you a lot of effort to develop from scratch.
It references the Bootstrap CSS library.
It references the jQuery library, which is a JavaScript library necessary for Twitter Bootstrap JavaScript modules.
It references the popper library. This is a JavaScript library that Bootstrap is using to position tooltips and popovers.
Finally, it references the Bootstrap JavaScript library too.
If you load the preceding page on your browser, you will see nothing. But all the Twitter Bootstrap features would be loaded.
container, which sets a max-width at each responsive breakpoint.
container-fluid, which is width: 100% at all breakpoints.
container-{breakpoint}, which is width: 100% until the specified breakpoint. After the specified breakpoint (including), it uses the max-width as if it were a container.
max-width defines the maximum width an element can have. This means that the element tries to occupy as much width as possible up to the max-width after which it expands its height in order to fit the content. This of course means that the actual width of the element cannot be more than max-width, even if the width property may have a larger value.
Twitter Bootstrap defines five breakpoints, that is, pixel widths, after which the grid layout changes. For example, a small breakpoint has the value 576px and is referring to displays with width between 576px and 767px. I will talk about breakpoints later on in this chapter.
You apply one of them by setting the corresponding div element (or equivalent block element) to have a class equal to the name of the container.
I have added a reference to a local CSS file named stylesheets/index.css. I have put that exactly after the Twitter Bootstrap CSS reference. I will put inside this file the web page–specific CSS rules. This file needs to be after the Twitter Bootstrap CSS reference, because it will be relying on it.
I have created two divs that would function as the page containers. The first div is a container, whereas the second div is a container-fluid.
Now that you are using Twitter Bootstrap, you will not need to write CSS reset rules like * {box-sizing: border-box}. This is because Twitter Bootstrap itself has a series of defaults that make very good sense, and they are aligned with the rest of the Twitter Bootstrap classes.
As you can imagine, this is used to apply specific, different colors to the two containers so that I can see how they are put on the page.

container vs. container-fluid
As you can see in Figure 1-4, the container has left and right margins, whereas the container-fluid does not have margins and covers the whole width of the page. container margins are not of fixed width. Their width changes depending on the viewport width.
On the other hand, both containers have left and right paddings, equal to 15px. You can see that the text “This is a container …” does not start at the edge of the left border, but it has some free blank space.

container Behaves like container-fluid on iPhone X
Hence, container and container-fluid in that case would be the same.
The grid system, that is, dividing your layout into rows and columns, is a good practice to design the layout of your page. Twitter Bootstrap comes with handy classes that will allow you to scale your layout up to 12 columns, as the device or viewport size increases.
Decide on the container type.
Inside the container, add a row class div.
Inside the row class div, add one or more col-* class div elements.
I will explain what a col-* class is using some examples.

One-Row 12-Column Grid
As you can see in the HTML file, index.html, I have used a container and inside it I have introduced a row class div. Then for each one of the 12 columns, I have used a col class div.
Again, I wanted 12 columns, and I added 12 divs with class col. All 12 divs have been added inside a single row div. The row div is used to lay out columns, and only columns can be immediate children of rows.

Two Rows, the Second Row with Six Columns
As you can see in Figure 1-7, each one of the columns of the second row occupies double the column width of the columns of the first row.
As you can see, it is very easy to have six columns by only having six divs with class col as children of the div with class row.

Second Row Having Five Columns, First Column Being Wider

Second Row Having Five Columns of Equal Size

What You Want to Achieve
In order to do that, you have to be more precise on the class of each column div. You have to tell exactly how many standard columns each column should occupy.

Another Way to Divide into Five Columns
As you can see in Figure 1-11, the second row is, again, with five columns, but with a different size for the first and third columns. These two are of size 3, whereas all the other columns are of size 2. However, even in this case, the total column sizes add up to 12: 3 + 2 + 3 + 2 + 2.

Middle Column to Be Half of Available Width
You want the middle column to be occupying half of the available width and leave the rest of the space shared between the first and third columns.
Name | Symbol | Display Width |
|---|---|---|
Extrasmall | xs | <576px |
Small | sm | >=576px |
Medium | md | >=768px |
Large | lg | >=992px |
Extralarge | xl | >=1200px |
You are referring to them by their corresponding symbol, as part of the class name that you are using.
So, if you are using, for example, the class col-lg-5, this means that this class refers to the breakpoint lg, for devices with width >=992px. However, further interpretation of each particular class depends on the class case itself. We will learn the most important classes in this section.
col-1, col-2, and so on, up to col-12, for the extrasmall devices
col-sm-1, col-sm-2, and so on, up to col-sm-12, for small devices
col-md-1, col-md-2, and so on, up to col-md-12, for medium devices
col-lg-1, col-lg-2, and so on, up to col-lg-12, for large devices
col-xl-1, col-xl-2, and so on, up to col-xl-12, for extralarge devices
But what is the difference between col-sm-2 and col-md-2, for example?
They both occupy two columns. col-sm-2 will occupy two columns for any display area width that is >=576px, but col-md-2 will occupy two columns only for display widths that are >= 768px. col-md-2, for display areas that are <768px, will not occupy two columns, but will stack one column above the other, as if they were two rows, essentially each column occupying the whole 12-column available width.

One-Row Six-Column Layout—Each One Occupying Two Columns
As you can see in the HTML code, I am using the breakpoint sm, and I instruct that each column occupies two of the available 12 columns. This will result in the row being divided into six columns, but only for display areas with width >=576px.

Exactly 576px Width—Still Six Columns in Width

Six Columns Stacked When Below the sm Breakpoint
This happened because I have used the class col-sm-2. Again, this class stacks the columns one on top of the other for each display width less than 576px and keeps the columns horizontal for any width greater than or equal to 576px.
As you can see from the preceding picture, the initially two-column-wide columns are now 12-column-wide, occupying the whole row.
The nice thing with Bootstrap is that you can apply multiple classes of different breakpoints on the same div, in order to adapt the grid layout for different devices.
See the following example in order to understand what I mean. Let’s suppose that I want, for small devices and above, to have six columns, but for smaller devices (less than 576px), I do not want one column per row, but two columns per row.
For small devices or larger, I want six columns. This means that I need to use the col-sm-2 class for the divs (sm for small and 2 for six columns, since 12/6 gives 2).
For extrasmall devices, I want two columns per row. Hence, I need to use the col-6 class for the divs (for extrasmall, I don’t interpolate the symbol of the device width into the class name, since the default value is xs and 6 for two columns, since 12/2 gives 6).

Two Columns on Extrasmall Devices
However, if you enlarge your display area to have a width greater than or equal to 576px, you will see that your page has six columns per row.
This is how the responsiveness of your grid is achieved.
One might say, “Hold on! When on extrasmall devices, the columns inside the div have a number suffix (-6) that adds up to 36, not to 12.” You need to know here that Twitter Bootstrap will automatically wrap the columns above the 12th to a new row.
The previous web page had one grid layout breakpoint actually—the 576px, whichever display width below 576px vs. whichever display width equal to or greater than 576px. You can apply the same concept to a second breakpoint in the same grid. For example, you may want the number of columns to be three for display areas greater than 576px (small) and six for display areas greater than or equal to 768px (medium or wider).
For extrasmall devices (<576px), two columns per row (hence, col-6)
For small devices (>=576px, <768px), three columns per row (hence, col-sm-4)
For medium or wider devices (>=768px), six columns per row (hence, col-md-2)

Three Columns on Small-Size Displays

Six Columns on Medium-Size Displays
You need to implement a multicolumn layout like the ones presented in the chapter. Here are the requirements of the grid depending on the display width:
For extrasmall displays, it should display one column per row.
For small displays, it should display two columns per row.
For medium displays, it should display three columns per row.
For large displays, it should display four columns per row.
For extralarge displays, it should display six columns per row.
Good luck!
The bare-minimum Twitter Bootstrap page and what it needs to include
The containers
The row divs
The col divs as children of the row divs
How to break the row into several columns of equal width or different widths
The different Bootstrap breakpoints
How to use different classes to define the layout of your page of different display widths
In the following chapter, you will use some more advanced techniques around the Twitter Bootstrap grid system.
In the previous chapter, you started learning about the Twitter Bootstrap grid system. In this chapter, you will continue your work on the grid system, but you will use some different, more advanced techniques to do similar and other things.
How to use row columns
How to vertically align content
How to horizontally align
How to use less than the 12 available columns
How to nest content and a grid inside another
What the Twitter Bootstrap defaults are
You are now going to explore one more set of alternatives in order to do all the things that you did in Chapter 1, “Getting Started.” This is called row columns, and it is a set of classes that help you define the columns of a row but using them at the row div, not at the col div.

Six Columns Using the row-cols-* Class
The row div was attributed with the class row-cols-6. The number 6 was exactly the number of the columns I wanted.
Then each column div only had the col class, since I wanted all the columns to have equal width.
Of course, I am now hearing you saying, “Hold on. The same would have been accomplished if I had used only the row class without the row-cols-6 class.” And you would have been right. The use of row-cols-* in the previous example didn’t add too much value. But let’s do another example in which the row column classes are much more valuable.
Three columns for all devices up to and including medium ones
Six columns for all devices with large or wider displays
I keep the column divs having only the col class.
row-cols-3 for all devices except the ones defined with the following class. Note the number 3 is the number of columns we want to occupy.
row-cols-lg-6 for all devices with large or wider displays, that is, >=992px.

Three Columns When Below 992px

Six Columns for 992px and Wider
col-* at Column Level | row-cols-* at Row Level |
|---|---|
<div class="row"> <div class="col-4 col-lg-2"> 1 </div> <div class="col-4 col-lg-2"> 2 </div> <div class="col-4 col-lg-2"> 3 </div> <div class="col-4 col-lg-2"> 4 </div> <div class="col-4 col-lg-2"> 5 </div> <div class="col-4 col-lg-2"> 6 </div> </div> | <div class="row row-cols-3 row-cols-lg-6"> <div class="col"> 1 </div> <div class="col"> 2 </div> <div class="col"> 3 </div> <div class="col"> 4 </div> <div class="col"> 5 </div> <div class="col"> 6 </div> </div> |
When I use classes to specify the column width at the column div level, I specify the number of columns (out of the 12) my column will occupy. For example, if I want my column to be three columns wide, I use col-3.
When I use classes at the row div level, I just specify the number of columns I want in the row. Then Bootstrap will automatically calculate the width of each column.
Obviously, when I use row classes, I set the width for all the columns of the row to an equal size. If I want to have columns with different widths within the same row, I have to use the column classes at the column-level div.
You have learned how to lay out things using a 12-column-wide grid, but Bootstrap allows you to align things inside the row itself, in the vertical axis.

Content in the Middle of a Tall Row
The difference is done by the class align-items-center at the row div. It instructs the browser to draw the columns that are children of this div at the center position of the row on the vertical axis.
The preceding CSS has the rule to apply min-height on the row divs. This will allow you to see the contents of the children divs in the center of the row on the vertical axis direction.

Use Various Vertical Alignments
Don’t forget to make your index.css have rules that will make your rows have minimum height so that you can see the vertical alignment. Listing 2-6 contains such rules.

Use Different Vertical Alignments Within the Same Row
I continue by explaining to you how you can align columns in the horizontal direction, which is more useful when you have content that does not occupy the whole width of the page.

Left-Aligned Columns
In Listing 2-9, the class justify-content-start is attached on the second and third row divs.

Center and Right Alignment
Hence, these justify-content-* classes at the row divs are useful, because they allow you to align without having to use empty divs.

Columns with Space Between

Content with Space Around
I will close this first encounter with Twitter Bootstrap by giving some advice on how you should nest a grid within another.
Nesting a grid within another is allowed and follows the same rules that apply to the root grid. How would you do it? You have to use a row div and child col divs inside the parent col div.

Nested Grid Inside Another
As you can see from the preceding code, inside the row div with class parent, I have a col div (with class col-6). This latter div has another row inside it (with class nested) that starts the nested grid.

Nested Grid Has Three Columns on Medium Devices
Twitter Bootstrap | Without Twitter Bootstrap | |
|---|---|---|
html element box-sizing | border-box | content-box |
html element font-family | sans-serif | Times |
html element font-size | 16px | 16px |
body element font-family | -apple-system,BlinkMacSystemFont,“Segoe UI”,Roboto,“Helvetica Neue”,Arial,“Noto Sans”,sans-serif,“Apple Color Emoji”,“Segoe UI Emoji”,“Segoe UI Symbol”,“Noto Color Emoji” | Times |
body element font-size | 16px | 16px |
body element line-height | 24px | normal |
body element color | #212529 | #000 |
body element background-color | #fff | rgba(0,0,0,0); hence transparent |
body element box-sizing | border-box | content-box |
body element margin | 0 | 8px |
You can read more about the Twitter Bootstrap defaults if you download Twitter Bootstrap, locally on your computer. You can do that by visiting https://getbootstrap.com/docs/4.4/getting-started/download/ and then clicking the button Download. This will download, among the others, ready CSS non-minified code (look for file css/bootstrap.css).
You need to implement a page that contains an image roster.
You need to use Twitter Bootstrap tools to make it responsive.
Here is how the page should look (Figure 2-13) on extralarge displays (>=1200px).

Task: Responsive Image Roster Page
The page should look like Figure 2-14 on medium (>=768px) and large (<1200px) devices.

How the Page Should Look on Medium and Large Devices
The page should look like Figure 2-15 on small and extrasmall devices (<768px).

Page on Small and Extrasmall Devices
The header is an h1 element.
The img tags should be styled with width and height 100% so that they occupy all the space they are given.
Good luck!
How to achieve vertical alignment
How to achieve horizontal alignment
How to nest a grid inside another
In the following chapter, you will learn Bootstrap by implementing a real project. It will have a responsive navigation bar that will change its appearance according to the width of the display.

Basic Template with a Top Nav Bar

This Is How a Site Looks on Mobile Devices

Menu Options Appear on Hamburger Icon Click
You will develop this web page, but at the same time, you will understand how the Twitter Bootstrap classes work.
Learn to build a navigation bar for your site, step by step.
Make the navigation bar responsive.
Learn how to create a button with the shape of a hamburger and how to make it unfold the menu options.
Learn how to make the content of a paragraph stand out.
Learn about how to make your main content area not be hidden by the navigation bar.
This and the following chapters will be teaching you the framework concepts while trying to create a project at the same time. Let’s start, then, with our first project.

Target Project 1—Basic Template with a Top Nav Bar
It has a navigation bar. This navigation bar is responsive. This means that when you resize your browser to mimic the size of a mobile phone, you will see something like Figure 3-5.

This Is How a Site Looks Like on Mobile Devices

Menu Options Appear on Hamburger Icon Click
There are other features on this website that you take for free from Twitter Bootstrap. For example, when you mouse over the options, you will see that the options change color and intensity.
Let’s try to build this website from scratch, using Twitter Bootstrap.
Save the preceding code into the file index.html and load the page on your browser. Note that the referenced stylesheets/main.css does not contain anything, for the time being. But create this file so that your page can find it.

Page with a Nav Bar and Menu Items but Not Styled
I guess that this was expected. The body element contained nothing but a block element nav and a ul with the menu options. Note that we are using the semantic HTML5 element nav, instead of just a div.

Added the Class nav on the ul Element
Let’s now make the menu items have some space around them, because, now, they are one exactly next to the other.

Menu Items Separated
You have added the class navbar-expand-lg on the nav element. This instructs the browser to expand the content at the lg breakpoint, that is, for displays greater than or equal to 992px. Apparently, you could have used another breakpoint, for example, the md breakpoint, if you wanted the menu to expand for displays with width >=768px.
You have wrapped the ul element into a div element with classes collapse and navbar-collapse. This makes the browser know which content it needs to collapse and expand.

A Blank Page on Width Less Than 992px

Menu Options Appear on 992px
If you go back and look again at the final result, you will see that there is the link with text John Woo, which is not hidden when the page shrinks to mobile size. It is always visible, and it is supposed to be a link that would take the user to the home page of the site. It is not part of the list of menu items.

Brand Link Is Separate from Menu Options
Adding the class navbar to the nav wrapping element
Adding the class navbar-brand to the anchor element
The navbar class on the nav wrapping element is crucial for the whole styling of the navigation bar, not only for the brand link.

Brand Link Standing Out on the Left
Use one of the navbar-dark or navbar-light classes at the nav element.
Combine it with a background color utility class.
The former is basically dealing with the font colors, whereas the latter is dealing with the background colors. Usually you would like to combine the *-dark class with the dark background colors and the *-light class with the light background colors.

Background Color Utility Classes
The color classes, navbar-dark and navbar-light, have been designed to expect the ul element to have the class navbar-nav. So we are going to add that too.

Coloring the Navigation Bar
Also, hover your mouse pointer over the menu options. You will see how the links are getting lighter.

Unstyled Button to Toggle the Menu On and Off
This is pretty bad. Indeed. But it’s a start.
The problem you have with the button, at the moment, is that it always appears. What you want is that it appears only on devices with width below the expanded breakpoint that you have set on the nav element. The breakpoint that you have set is lg, which means that you want the button to appear for displays with width <992px.

Menu Is Visible; Button to Toggle Is Not Visible (>=992px)

Menu Hidden, but Button Present (<992px)
The button appears in a way that is very hard to see. This is fixed next.

Hamburger Icon Now Present
data-toggle="collapse", which tells Twitter Bootstrap that this button is used to collapse/unfold a specific area of the HTML document
data-target="#navbar", which tells Twitter Bootstrap that the specific area that needs to be collapsed/unfolded is the one that is selected with the CSS selector #navbar. Of course, since there is no such element (with id navbar) in your HTML document, but the element that you want to fold/unfold is the container that holds the menu items list, you will add the id attribute with value navbar to this particular div. Let’s do that (Listing 3-10).

Menu Expanded After Clicking the Button
fixed-top on nav element will fix the position of the navigation bar at the top of the page.
You will also add some elements and attributes to make the whole navigation bar ready to be used with assistive technologies, for example, with screen readers.
You will also add the class active to the first menu item, to indicate that you are on the page that this link corresponds to.

Final Page with a Navigation Bar on 992px
Your navigation bar works perfectly, and you have not written a single line of CSS or JavaScript code. Isn’t it amazing? All thanks to Twitter Bootstrap.
You have added a div with the class container below the nav element. Inside this new div, you have added an h1 and a p element with some content inside them.

Main Content Hidden Behind the Top Nav Bar
You can see the problem, I guess. The h1 header is hidden behind the top navigation bar.

Calculate the Height of the Top Navigation Bar
As you can see from the developer tools, the height of the top navigation bar is 56px, calculated by adding the top and bottom paddings and content height.

h1 Is Now Visible
There are some small differences to the original site. One is that the paragraph content is plain, normal-size text. You want to make it stand out . You will use the class lead for that (again provided to us by Twitter Bootstrap).

Paragraph Stands Out

Nav Bar Content Misaligned with Page Main Content

Nav Bar Content Aligned with Page Main Content
Well done! This matches the original page that you wanted to build.
You have created a website with a responsive navigation bar, without writing any single piece of CSS code. Twitter Bootstrap has provided everything to you. You only had to use the correct classes (and in one case, two data-* attributes).

Task Project with a Navigation Bar
The main content should be centered.
There is a lot of blank space above the main content and below the navigation bar. Make sure that you have the same on your page.
The navigation bar should be responsive, and when you load your page on small displays, the menu items should be hidden. In their place, a hamburger icon should be displayed. The icon, when clicked, will unfold the list with the menu options.
Good luck!
How to implement a navigation bar with menu options that are hidden on small devices and visible on large devices.
For small devices, you have implemented a button that when clicked toggles on/off the menu with the options.
You have also learned how to color the navigation bar and how to position it.
You have learned how to put content on the main page without it being hidden by the top navigation bar.
You have learned how to make a paragraph stand out.
In the following chapter, you are going to get acquainted with the most popular Twitter Bootstrap components, like buttons, badges, tabs, and so on.
In the previous chapter, you have created a small Twitter Bootstrap project. Now, you are going to create a page that would reference some of the most commonly used Twitter Bootstrap components.

Dropdown Menu in the Navigation Bar

Jumbotron Example

Button Example

Table Example

Label Example

Badge Example

Tabs Example

Alert Example

Progress Bar Example

Card Example
And finally, you will learn how to create the impressive image carousels.

Twitter Bootstrap Example Page with Various Elements
Learn how to add a dropdown menu in the navigation bar.
Learn about the various dropdown menu components and classes.
Learn about jumbotrons.
Learn about page headers.
Learn about styling buttons.
Learn about how to style tables.
Learn how you can create labels and tags.
You continue working on Twitter Bootstrap projects, and you will now build a project that will work as your reference to various Twitter Bootstrap components.
Let’s start.

Starting Page

Page with a Dropdown Menu
If you save the preceding code and load the page on your browser, you will see the new dropdown menu on the far right.
The list item (li) that will work as a dropdown menu needs to have the class dropdown.
The dropdown list item text, in our case Dropdown, needs to be wrapped into an anchor <a> HTML element. This will make the pointer change, when the user hovers over it. Note that the anchor needs to have the class dropdown-toggle and the data-toggle attribute equal to dropdown.
The list of options of the dropdown menu can be given inside a div.
The div needs to have the class dropdown-menu .
Each menu option is given with an anchor a that has the class dropdown-item.
You can use a special, empty div with the class divider if you want to create a line in between menu items that would function as a divider.
You can also use another special div that would function as a submenu header and will not actually be part of the user options, that is, wouldn’t be possible to click and select. This can be done if the div has the class dropdown-header.
After the nav, you are creating a .container div to include the content of your page.
The first thing that you create is a div with class .jumbotron.

Jumbotron with Header and Lead Paragraph
Note that the space between the bottom side of the navigation bar and the top side of the jumbotron is created by the padding-top rule inside the main.css file.
The approach here is very simple. We use the class jumbotron for the div. We also use the header h1 for the header text inside the jumbotron.
Finally, we have already seen, in the previous chapter, the class lead that is applied on the p element to make the text stand out.
There are times that you want to create a header, that is, a piece of text that stands out like a header, for example, h1 or h2, and below that a horizontal line.

Page Header with Horizontal Line
The prefix m stands for margin. Hence, in your example, you are applying some margin to the hr element.
The y refers to the vertical y-axis. Essentially, it is about the top and bottom sides of the element. Hence, in your example, you are applying some top and bottom margins to the hr element.
0: Which sets the size of the margin or padding to 0
1: Which sets the size to 0.25 times the $spacer size ($spacer * 0.25)
2: Which sets the size to 0.5 times the $spacer size ($spacer * 0.5)
3: Which sets the size equal to the $spacer size
4: Which sets the size to 1.5 times the $spacer size ($spacer * 1.5)
5: Which sets the size to 3 times the $spacer size ($spacer * 3)
Auto: Which automatically sets the size (applies to margins only)
OK! Hold on! What is the $spacer? The $spacer is a Sass (Syntactically Awesome Style Sheets) variable. Note Bootstrap is written in Sass and then it is compiled to actual CSS. The default value of the $spacer variable is 1rem.
If this is too complicated, there is no other way to clarify it but to play and try things out. Also, your best friend is the developer tools of your browser.

24px Margin Top and Bottom, Thanks to my-4

my-4 Gives 1.5rem Top and Bottom Margins

The font-size of the Root Element Is 16px
And why is 1.5rem computed to be 24px? rem is a CSS unit that calculates the size of an element relative to the font-size of the root element of the page, that is, of the html element. If you inspect the font-size property of the html element using the developer tools, you will see that it has size equal to 16px (Figure 4-18).
Hence, 16px * 1.5 calculates to 24px.
I did a small deviation to discuss CSS units and how they are used in an HTML document. This is not part of Twitter Bootstrap. You can learn more about HTML and CSS in my book Master HTML & CSS.
All buttons should have the class btn.
btn-default
btn-primary
btn-secondary
btn-success
btn-danger
btn-warning
btn-info
btn-light
btn-dark
Instead of a color, you can also apply a class to turn a button into a link: btn-link.
Or you can interpolate the *-outline-* word in the class name in order to style a transparent background color button with a border, for example, btn-outline-primary.
Then you can specify the size of the button using a corresponding class:
btn-lg for large buttons.
Specify no class for normal-size buttons.
btn-sm for small buttons.
btn-block for blocks that span the whole available width.
As you can see in the preceding code, this is a series of header h2 and p elements that apply to all the combinations of classes I talked about earlier.

Page Demonstrating Buttons
On this page, you can see how each button is displayed, according to the Twitter Bootstrap button classes that you have applied. It is really impressive, because without a single line of CSS code, you have so much functionality for free. You only have to learn the various Twitter Bootstrap classes.
You have already learned about the tables and how they should be used to display tabular data (from my Master HTML & CSS book). Twitter Bootstrap comes with some useful classes on how to style tables. Let’s see how.
Let’s start with a table that does not have any Twitter Bootstrap class applied. So it is only with its default style.

Tables Without Any Extra Styling

Tables with the “table” Class Only
for the second table.

Striped and Bordered Tables
The table-striped class makes the table have stripes, one row being with a dark background and the next one with a bright one. The table-bordered class adds borders to the table.

Table Bordered and Striped at the Same Time
If you save and load the page on your browser, you will see the table as it was with the table class only. But if you try to move your mouse pointer over the rows, you will see how rows are highlighted as the mouse moves over them.

Small Height with the table-sm Class
As you can see in Figure 4-24, the second table with its condensed style has significantly smaller height for its rows, if compared to the height of the rows of the first table.
Furthermore, Twitter Bootstrap offers a series of semantic classes that correspond to specific colors. When you apply those classes, you quickly set the background color of the corresponding row (tr) or the corresponding cell (td or th).
table-active
table-primary
table-secondary
table-success
table-danger
table-warning
table-info
table-light
table-dark

Table with Different Classes at Row Level
Bootstrap allows you to create labels and badges very easily.

Tag Example
badge-primary
badge-secondary
badge-success
badge-danger
badge-warning
badge-info
badge-light
badge-dark

Labels Demonstration
Pretty clear. Please, keep note that you have enclosed the spans inside an h4 element just to make them a little bit bigger.

Badge Example
These are not different from the labels we have created earlier. The only difference is that they are more rounded. You can achieve this by adding the class badge-pill alongside the other badge-* classes.

Buttons with Badges
Navigation bars with dropdown menu lists
Buttons, with various sizes and colors
Tables with different styles
Labels and badges
This is the end of the first part of the Theme Reference project. In the following chapter, the second part of the project, you will continue learning more about Twitter Bootstrap components.
In Chapter 4, "Theme Reference: Part 1," you have learned about some of the most important Twitter Bootstrap components, and you have started creating a reference page for all of them. In this chapter, the second part, you continue with some more components, within the same reference project.
Tabs, which are used to group information
Alerts, which are used to display a standout message
Progress bars, which are used to visually show to the user the percentage of a work under process already done
Cards, beautiful rectangular areas with rich content that draws viewers' attention
Carousel, a component that works like an image or some other rich content slideshow

Twitter Bootstrap Example Page with Various Elements
Learn how you can create tabs.
Learn how you can create alerts.
Learn how you can create progress bars.
Learn how you can create cards.
Learn how you can create carousels.
You continue working on the Twitter Bootstrap Theme Reference project that you started in the previous chapter. Let’s start adding more components into it.
Sometimes you want to organize the information on your page using tabs. The tabs are good because they group parts of the information under a title and they do not display all the information at the same time. The user selects which information group to see/read by clicking the corresponding tab header.

Example of Tabs
The information displayed is changed according to the tab header being clicked.
Let's see how we can implement the preceding tabs example.
The tab headers
The different contents with the actual information
The tab headers are an unsorted list ul with class nav nav-tabs. Each element in the list (li) corresponds to a tab header, and it has to have the class nav-item. The content of each li is an anchor with class nav-link and the data attribute data-toggle with value tab. Also, each anchor has an href value pointing to the corresponding information container. When this anchor is clicked, that information container is going to be displayed to the user. Note that the li corresponding to the information container that should be displayed to the user needs to have the class active too.

Tabs with Empty Content
That's a good step. You can see how the tabs are well put on the page. You can even click the headers in order to see how the active tab changes according to the tab that you click.
What is missing now is the information that should be attached at each tab.
You put the tab information inside a div with class tab-content. Inside that, we create one div per information group/tab header. This div needs to have a class tab-pane. Also, it needs to have the correct id, different for each tab information panel and corresponding to the href value of the corresponding tab.
You have a div that contains all the other individual divs.
This parent div has class tab-content.
Each div has id value equal to the href of the corresponding tab header anchor.
Each div has the class tab-pane.
The first div has the class active too, because this is the first information box that is displayed for the first tab header, which is also, initially, active.

Tabs with Content
As you can see, the tab information is clearly displayed below the tab headers. Also, if you try to click different tab headers, you will see how the following information changes accordingly.

Problem with the Tab Content Being Too Close to Tab Headers
In order to fix this, you need some bottom margin on the ul that includes the headers. You can achieve that by adding the utility class mb-3 to the ul element.

Tab Content Now Has Some Free Space Above It
Twitter Bootstrap is encouraging the authors to make their content compatible with assistive technologies, such as screen readers. This means that instead of just using the styling classes, you may also have to add some extra HTML attributes specially designed for this purpose. For example, the role HTML attribute for the ul element with the tab list needs to have the value tablist. If you want to learn about how you can create accessible rich Internet applications, you have to read and apply the practices given here: WAI-ARIA Authoring Practices.

Alert Example
These messages are usually displayed at the top of the page, but not necessarily only there.
Twitter Bootstrap gives the class alert that should be used on a block element (like a div) in order to turn it into an alert block. Alongside that, you also need to specify a class that would color the alert so that it better conveys the message to the user. So, for a message that would indicate warning, you could use the alert-warning class, alongside the alert one.
alert-primary
alert-secondary
alert-success
alert-danger
alert-warning
alert-info
alert-light
alert-dark

Alerts Demo

Alert with Hyperlink Inside

Styling Links with alert-link

Progress Bar Example
As you can see in Figure 5-11, the progress bar has both a color and a text indication of how much of the process has been completed and how much is left to be done.
As you can see from the preceding fragment, the progress bars are very easy to build. A div has the class progress; and another div, inside the first, has the class progress-bar. The child div has the text that is displayed to give a textual info about the current progress. This text is not necessary. It might be empty. The important part here is that you correctly set the value for the width attribute of the child div, so that it is that big to indicate the actual progress. A good approach is to use a percentage here, because the percentage will make the child width be a percentage of the width of the parent div. The progress class on the parent div makes sure that the parent div occupies all the available width of the page, whereas the style="width: 60%" on the child div makes sure that the child div occupies exactly 60% of the parent div, hence these two div elements working as one to give the visual effect of the progress bar.

Standard Progress Bar

Adjust the Height of the Progress Bar
bg-primary
bg-secondary
bg-success
bg-danger
bg-warning
bg-info
bg-light
bg-dark

Progress Bars with Various Colors

Multicolored Progress Bar
As you can see in the preceding code, all three different color divs are inside the parent div. Twitter Bootstrap is clever enough to draw each one of them at the correct position and, given the classes for the color of the progress bars, to draw them with the correct color.

Card Example
A card usually has an image, a title, and a body. But it can also contain headers and footers.

Cards in Your Twitter Bootstrap Reference Page
You are going to add three cards.
For displays up to 767px, it will display one card per row.
For displays up to 991px, it will display two cards per row.
For displays with width >=992px, it will display the three cards on the same row.
The row-cols-* are the ones needed in order to lay out one or two or three columns on the desired breakpoints.
All of this is needed so that you can achieve the responsive layout that is required.
The whole card is enclosed inside a div with the class card.
Each card has a header, which is an h* element with class card-header.
The image is constructed with a standard img element that has the class card-img-top. You have also given a specific height so that all the images of all the cards are displayed on a specific height, but taking all the available width.
Then, the main content of the card, the one that follows the image, is put inside a div with class card-body.
A card title using an h* and a class card-title.
A card subtitle using an h* and a class card-subtitle.
A paragraph with the main text. This has the class card-text.
A hyperlink with class card-link and some extra classes to make it look like a button.
After the body, we attach a div with the class card-footer. This is used to create the footer of the card.
That was it. If you save the HTML page and load it on your browser, you will see the cards that you have already seen in Figure 5-17.
You will close this long Twitter Bootstrap reference page with a really cool feature which is called a carousel. Twitter Bootstrap allows you to create image and video carousels. Carousels are areas of the page that display a series of images (and/or videos) one by one. Each image stays visible for a while (about 5 seconds) before being replaced by the next one.
Small indicators usually displayed at the bottom (Figure 5-18)

Carousel Indicators
The number of indicators is equal to the number of items in the carousel. In the preceding example, there is a carousel with three items. Hence, you can see three bars. The one that is filled with white color indicates which item is currently displayed. You can also click a bar to quickly display the item at the corresponding position.
Next and previous controls (Figure 5-19)

Carousel Next and Previous Controls
Next and previous buttons, like arrows, allow you to navigate, slide, from item to item, in either direction, left or right.
The items (Figure 5-20)

Carousel Items and Titles
The carousel has a list of items, each one referencing an image and having a title.
The carousel needs to be enclosed inside a div with classes carousel and slide. If you also want to transition from one slide to the next with a fade effect, then you have to add the class carousel-fade too.
The main div needs to have an id, like the one we have in the preceding HTML fragment (carousel-example-generic). This is necessary because it is then referenced by the indicators and the controls. This requirement becomes more important if you have more than one carousel on the same page.
They need to be an ordered list (ol) with class carousel-indicators.
Each item (li) is an indicator, and you need to have as many indicators as the number of your items. If you have three images, then you have to have three indicators, that is, li items.
Each indicator needs to have a data-target attribute with the id of the carousel. Also, it needs to have a data-slide-to attribute with value equal to the index/position of the item it corresponds to. Note that indexing/positioning starts from 0. That is, the first carousel item is referenced with index 0, then the second with index 1, and so on.
The first indicator needs to have the class active.
All the carousel items need to be wrapped in a single div with class carousel-inner.
Each one is a div that has the class carousel-item.
The first one needs to have the class active; otherwise, the carousel will not be displayed.
Classes d-block and w-100: The first (d-block) sets the image display attribute block value. The second (w-100) sets the image width to be 100%. Hence, the image will occupy the whole width available. Note that these are display and sizing Bootstrap utility classes.
Style that sets the height of all images to be the same. In the example, it is set to 500px.
d-none, which hides the captions.
d-md-block, which displays the captions for medium displays and wider. In other words, you want the captions to be displayed on devices with width >=768px. Otherwise, they will not be displayed.
The first has the class carousel-control-prev, and it is used to navigate to the previous/left slide.
The second has the class carousel-control-next, and it is used to navigate to the next/right slide.
Both have attribute href pointing to the carousel id (#carousel-example-generic).
Both have a child/content that is a span. This span is used to display the left (for the first control) and the right (for the second control) arrows. For the first control, the span needs to have the class carousel-control-prev-icon, so that it displays the left arrow. For the second control, the span needs to have the class carousel-control-next-icon, so that it displays the right arrow.
This closes a long encounter with Twitter Bootstrap. You have created a page with a big list of Twitter Bootstrap features that can be used as a reference to the most commonly used features.
However, there is a lot more to cover on Twitter Bootstrap. This will be done in the next chapters.
Tabs
Alerts
Progress bars
Cards
Carousels
In the following chapter, you are going to learn how Twitter Bootstrap can help you create a page whose background is covered with an image.
This chapter teaches you how to style the navigation bar and how to have a background image to cover the whole page of your site. Also, it teaches you a technique to vertically align content irrespective of its height.

Cover Page Project
Learn how to pull the non-brand options of a navigation bar to the right.
Learn how to center content both vertically and horizontally using the table/table-cell technique.
This is a chapter that will teach you how to create another nice-looking Twitter Bootstrap project. I call this a cover page project because it encompasses a large background image that covers the whole browser page. All the content appears on top of this page.
The purpose of this exercise is to combine some Twitter Bootstrap knowledge with some techniques that you have learned in the book Master HTML & CSS and that are not Twitter Bootstrap specific.

Page That You Will Build
There is a background image that covers the whole page.
The image covers the page no matter what the size of the page is.
Although the original image is bright, the image displayed on the page has reduced brightness. This helps the text that overlays the image to have a better contrast and be easier to read.
The top navigation bar is similar to the navigation bars that we have built earlier. However, the non-brand part of the options is aligned to the right.
The main content of this page is vertically and horizontally centered.
There is a footer fixed at the bottom of the page, with text horizontally aligned at the center.
Save the preceding file as index.html and also create an empty file stylesheets/main.css. If you load this page on your browser, you will see an empty page, but with Twitter Bootstrap loaded .
This is pretty standard.

Background Image Applied to the Body Element
As you can see in Figure 6-3, the image is clearly displayed . It covers the whole browser window, and if you try to resize the window, you will see that it is being automatically adjusted to cover the new window size.
Let’s see how we can reduce the brightness of the image . We can definitely change the brightness of the image using an image editing software like GIMP or Adobe Photoshop. But, if you do not know how to do that or if you do not want to change the original image, you can always do the following trick.
You define a div element, as a child of the body element. This div will be positioned absolutely at the top-left corner of the page and will cover the whole width and height of its parent body element. Let’s call this div cover div. The cover div needs to have a black background color, but with some transparency so that some of the image colors behind it will be visible. You can try rgba(0, 0, 0, 0.5) for that.
Let’s do that.
As you can see in the preceding code , it is a prerequisite for the position: absolute; on #cover to work correctly for its parent element, body, to have a non-static positioning. That’s why we set the position: relative; to the body element.

Black Cover with Transparency Applied
This is exactly the result that you want to achieve. The background image is, now, a little bit dark, so any text that you will overlay on top of the background image will be easy to read.
We are now going to attach a navigation bar, like we did in the previous chapters.

Added Standard Bootstrap Navigation Bar

Brand Link Before the Toggler Button

Toggler Appears on the Far Right

Toggler Left, Brand Link Right
The navigation bar has some margins, left and right. It does not occupy the whole width of the page.
Also, it has some margin above it.
Finally, its border has rounded corners.
Before you actually implement the preceding requirements, you will also set one more. You want the navigation bar to be full width for extrasmall and small devices, but only 50% of the page width for all other cases.
As you can read from the preceding code, the default width of the navigation bar is 100%, since it is a div. You are using a @media query rule in order to turn that to 50% for larger devices.

Navigation Bar as Displayed on Large Devices

Navigation Bar Occupies the Whole Page Width on <768px Devices
Further working on the navigation bar, what you want to achieve now is to pull the non-brand options of the menu to the right. This can be easily done with the ml-auto Twitter Bootstrap utility class that needs to be applied to ul holding these options.
The ml-auto is translated to margin left auto. In other words, the left margin of the ul element will automatically be set to the maximum available.

Options Moved to the Right
You have not finished with the navigation bar yet. If you compare the current version to the original one, you will see that the font size and colors are different.

Navigation Bar with Required Font Size and Color
These are the required font size and color properties. And with this, you finished the work on the navigation bar.

Content on the Center of the Page
Add the preceding code below the nav element, before the end of the body element. This is all pretty simple HTML code. You have already learned about this in the previous chapters.

Content Placed on the Top Left—Cannot Be Easily Read
As you can see, the content has been placed on the top left. And it is not easy to read. This is where we have to introduce our z-index skills, because it seems that the #cover div is being drawn after the content we just put earlier.
body is positioned, because it has position relative.
#cover is positioned, because it has position absolute.
#navigation-bar-container is positioned, because it has position fixed.
If you read Chapter 23, “Element Positioning,” of my previous book Master HTML & CSS, you will know that positioned elements and non-positioned elements will play well if you control the stack context they belong to. And a new stack context starts whenever you use the z-index property with value different from auto.
In other words, you are going to start a new stack context by setting z-index: 0 to the body element. Then, the #cover is going to have a z-index equal to -1, because you want it to be behind every non-positioned element inside the body element. Again, make sure you read the last part of Chapter 23, “Positioning,” in my previous book Master HTML & CSS, in which I explained the order in which things are drawn by the browser.

Content on Foreground but It Is Still Difficult to Read Text
You can tell from the colors of the button that the content is now drawn on the foreground. But still, you cannot easily read the text, although this is only a problem of the color of the text.
Let’s change the color first. You will make sure that the color of any text element is white. Add color: white; to the body element in your CSS file.

Content Now with Correct Color
That’s good. The content color is looking good. Now, you need to fix the position.
You will tell the browser to assume that the div that contains the main content is a table cell. You will do that by setting display: table-cell; for this element.
You will tell the browser to assume that the parent element, a.k.a. the body, is a table. You will do that by setting display: table; for the body element.
You want the table (body) to occupy all the available space defined by its parent (html). For that reason, you will define width:100%; height: 100%; for the body element.
You want the document root to occupy all the available space given by the browser window. Hence, you will set width: 100%; height: 100%; for the html element too.
You will tell the table cell (center-content div) to center its content both horizontally (text-align: center;) and vertically (vertical-align: middle;).

Content Correctly Placed on the Center of the Page
There are other techniques that one can use to center content vertically. This technique, with table/table-cell, makes sure that even if you change the actual content, the margins, top and bottom, will be adjusted automatically.

Footer Added but Layout Destroyed

After Correcting the Footer Position, the Page Is Ready
After correcting the footer position , the page is now ready.
You have seen how you can have the navigation bar options be on the right side of the bar. You have also learned about a technique to center content vertically and horizontally.
Create a web page like the following (Figure 6-20).

Task, Cover Page—Visit Athens
It is similar to the page you have built in the chapter. There is a difference though—on the navigation bar. Can you see that?
How to style the navigation bar and bring the links to the right
How to display a background image
How to display content on the center of the page
How to position the footer at the bottom of the page
In the following chapter, you are going to learn how to create an admin dashboard page.

Basic Admin Dashboard
A site like the one in Figure 7-1 has the sidebar on a fixed position. The sidebar disappears on extrasmall devices, and the dashboard changes its layout according to the device display width.
Also, the table is responsive and can be displayed equally well on both large and small displays.
You will also learn various other new concepts like how to display an image in a circle shape or how to alter the text color using text color–specific classes.
Learn how to use a container or container-fluid element inside a navigation bar.
Learn about attaching a search form in the navigation bar.
Learn how to move the navigation bar search form to the right.
Learn how to define the correct vertical position of the navigation bar search form.
Learn how to quickly style input controls with the form-control class.
Learn how to create a sidebar, on the left.
Learn how to make the sidebar extend on full height.
Learn how to make the sidebar stay in the same position even if the user scrolls the main content of the page.
Learn how to use the visibility classes to show and hide parts of your page according to the display width.
Learn how to add a border on one side of a div.
Learn how to make a div occupy 100% of the available height.
Learn how to make the content of an ul element occupy the whole available width.
Learn how to create nice page headers with a horizontal line at the bottom.
Learn how to display images in a circle shape.
Learn about the text alignment classes.
Learn how to use responsive images.
Learn about the classes that affect the text color.
Learn how to create responsive tables.
Learn how to apply multiple Twitter Bootstrap techniques in order to create an admin-like layout.
In this chapter, you will create a basic admin dashboard page, using Twitter Bootstrap facilities.
This is a long chapter with many new things for you to learn. But, after you do some little extra work, you will be rewarded by the final result.

Basic Admin Dashboard
It has a navigation bar, the content of which extends the whole page width.
The navigation bar non-brand options are aligned to the right.
The navigation bar has a search form inside.
There is a left sidebar with navigation options. Let's call it a left-side navigation bar.
The left-side navigation bar is not displayed on extrasmall devices (Figure 7-3).

Admin Dashboard on Extrasmall Devices
The first thing that you will add and work with is the navigation bar.

Adding the Navigation Bar

Navigation Options Pulled Right
You want to add a search form inside the top navigation bar. This will not be part of the list of options, but it needs to be part of the div that collapses when you switch to small devices, that is, part of the #navbar div.

Search Form in the Navigation Bar

ml-auto Class on the Search Form
The search form is not positioned at the far right, but to the left of the options, because you need to remove the ml-auto class from the ul. You can’t have both on the search form and on the ul element.

Search Form Positioned on the Right
Use the class form-inline on the form HTML element.
Use the class form-control on the input HTML element.

Search Form with Styling Classes

Search Form and Menu Options on Small Devices

Search Form with Top Margin
And reload the page on your browser. Switch to the small-display (e.g., iPhone X) devices. When you unfold the menu, you will see the search form with the top margin looking much better, like what is depicted in Figure 7-11.

Search Form Top Margin on Large Displays
You want the mt-3 only on small devices when the menu options collapse.
You don’t want the mt-3 when the menu options are expanded.
Again, the preceding markup preserves the mt-3 on devices with display less than the lg breakpoint and uses the class mt-lg-0 on displays above the lg breakpoint.
If you save the preceding code and reload the page on your browser, you will see that the navigation bar is back to its correct style. And shrinking to a small display, it still works as expected.
You have used margin utility classes to align the items of the navigation bar to the right. But Twitter Bootstrap heavily relies on flexbox . It provides classes that can be used to align content accordingly.
You have written the form markup after the ul markup.
You have added the class flex-row-reverse on the div that contains both the menu options and the search form.
You have removed the margin classes from the form markup.

Using flex-row-reverse to Draw Items on the Right
As you can see, the direct children of the flex-row-reverse div have been drawn in reverse order, that is, first the search form and then the ul element.

Search Form Appears at the Bottom
All good! Now, let’s move to the left-side navigation bar.

Left-Side Navigation Bar Properties
Its background color is not white; it is more like a gray.
The active menu item has white color and blue background color.
There are three groups of menu items, a.k.a. three different lists.
It occupies a specific width of the page. Let's assume one-sixth of the width for medium, large, and extralarge devices (a.k.a. two columns out of 12) and one-fourth of the width for small devices (a.k.a. three columns out of 12). On extrasmall devices, the sidebar will not be visible.
As you can see in the preceding code, we have a div for the sidebar that uses the grid class col-sm-3 for small devices, hence occupying three columns out of 12, and the class col-md-2 for medium, large, and extralarge devices, hence occupying two columns out of 12.
The main content will go inside the second div, which also uses grid classes col-sm-9 and col-md-10 so that it occupies the rest of the available width. For small devices, it will occupy nine out of 12 columns; and for medium, large, and extralarge devices, it will occupy ten out of 12 columns.
Save the preceding content. If you load the page again on your browser, you will not see any difference, because the sidebar and main content do not have any actual content inside.

Left Sidebar—Lists Added
One problem that you see now is that the top list is hidden by the navigation bar. This is a problem that you have faced in the past. You need to give some top padding to the body content, at least equal to the height of the navigation bar. You will give 56px.

Lists Are Not Hidden by the Navigation Bar
That's an improvement. Now, you will apply the class nav on the lists. As you remember from previous chapters, the nav class on ul elements removes the default bullets displayed on the list items.

Class nav Applied to ul Elements
The class nav has removed the bullets from the elements of the lists. But it has also done something else. It has turned the ul elements to display flex, with flex-wrap equal to wrap. That’s why you see the li elements one next to the other.
Since you want your lists to be enlisted top to bottom, you can add the class flex-column that will make all the direct children to be drawn in a column.

flex-column Class Applied
The left sidebar starts to look much better. Yet, it is not finished.
Class d-none will hide the element.
Class d-sm-block will display the element for any display above the sm breakpoint.

Left Sidebar Hidden on 575px Displays

Sidebar Visible on 576px Displays
Don’t forget to add the class sidebar to the div that contains the three ul elements with the left-side navigation bar options.

Some Styling on the Sidebar
The preceding styling sets the background color and border on the right side of the sidebar and also some padding on the top and bottom.
You now want to make sure that the sidebar height occupies the whole available height. In order to do that, you need to specify height: 100% both on row div and on all of its ancestor elements.

Sidebar Occupies the Full Height
You will make sure that the user can tell one group of options from the next. You will apply a bottom margin on the ul elements of the sidebar.
You will increase the height of the elements in the list so that the options are quite distinct and there is some vertical space from one to the next.
You want the lists to occupy all the available width. So that when one moves the mouse pointer over any of the elements, the highlight goes from left to right. In order to achieve that, you will remove the left and right padding from the sidebar container.
However, you want each list item to have some padding so that the text does not start at the left edge of the bar.

Further Styling of the Left Sidebar

Options with Colors

Hover Over a Nonactive Option

Dashboard—Top Area with Graphs
There is a Dashboard header with horizontal lines at the bottom. You can create this effect with an hr and the class my-4 that you have seen in previous chapters.
You can see four information containers (graph image + text).
On extralarge displays, the information containers displayed on one row are four. Same goes for large and medium devices. On small and extrasmall devices, we display two information containers per row (Figure 7-28).

On Extrasmall Devices—Two Information Containers per Row
You will use some placeholder images for the graph images.
Let’s start.

Dashboard Page Header Added
That was pretty easy, and you have done that in the past. You can now see the Dashboard styled as a page header with the help of the hr element and the class my-4.
An image, an img element
A small label, inside an h4 element
A span with some text displayed below the label
The div has grid classes col-6 and col-md-3. On extrasmall and small devices, each information container block will occupy half of the available width (six out of 12 columns). Hence, you are going to have two such columns on each row. On larger devices, it will occupy a quarter of the available width (three out of 12 columns). Hence, you are going to have four such columns on each row.

Dashboard—Information Containers Put on the Page
Now, information containers have successfully been put on the page, below the page header. But you need to do some style tuning in order to achieve the desired result.
Let's first make sure that the images are displayed with a circle shape. This is very easy to do. You only have to add the class rounded-circle on the img elements.

Information Containers Have Images with Circle Shape
Next thing that you want to do is to make sure that both the image and the text of the information container are center aligned. You will use the class text-center to all the div elements that wrap the image and the text.
text-left: Corresponds to text-align: left;
text-right: Corresponds to text-align: right;
text-center: Corresponds to text-align: center;
text-justify: Corresponds to text-align: justify;
Also, you can use these classes with their breakpoint-specific variation. For example, you can use the class text-md-center, which will center the content but only for medium or wider displays.

Content Aligned on the Center

Images Are Not Displayed OK on iPad

Images Are Displayed OK with the Class img-fluid
It sets the max-width to 100%. This means that the image width cannot be wider than the parent block the image is in.
It sets the height to auto. This means that the height will automatically be calculated based on the width, so that the image has the correct aspect ratio.
With these restrictions in place, the images end up drawn correctly on any display size.

Color of the "Something else" Phrase
text-primary
text-secondary
text-success
text-danger
text-warning
text-info
text-light
text-dark
text-body
text-muted
text-white
text-black-50
text-white-50

Bootstrap Text Color Utility Classes

"Something else" Phrase with the text-black-50 Class Applied
The next part on the admin page is the dashboard table. You have already learned how to design tables using Twitter Bootstrap. So this will not be a difficult exercise.

Section Title Is Not Displayed

Section Title at the Bottom of the Page

How Nested Div 100% Height Affects Layout
The > is the direct child selector. The preceding CSS rule selects the #main-container as well as its first-level direct child element with class .row.

Section Title at the Correct Position

Section with Some Top Margin

Table Is Correctly Displayed

Table Is Badly Styled on Mobile Devices
There is a very easy way you can fix this problem. You can use the Twitter Bootstrap class table-responsive . You need to give this class to the table element. In fact, it may be a better idea to set it only for the extrasmall, small, and medium devices. For large and extralarge devices, you can have the table behave as default.
Hence, go ahead and attach the class table-responsive-lg to the table. This class does the following: From the lg breakpoint and up, the table will behave as normal. But below this breakpoint, that is, for displays <992px, it will get, automatically, without you having to add it in your CSS rules, an overflow-x: auto;, which will allow the user to scroll horizontally in order to see the whole content of the table.

Table Displayed Correctly on iPhone X
If you scroll horizontally, you will see how the rest of the page is still being displayed correctly.
You have managed to bring the page to look exactly like the page you initially had as a target. There is a small improvement that I would like to work with you on.

Problem with the Left-Side Navigation Bar
As you can see, there is a problem with the left-side navigation bar. The options disappear, as the sidebar content scrolls along with the rest of the main content. You want all the sidebar options to be accessible and visible all the time, so that the user is able to click them irrespective of the actual scroll position of the main content.

Sidebar with Fixed Position—Problem on Main Content
This is an improvement with regard to the sidebar being on a fixed position. Try to scroll the main content; and you will see that the options on the sidebar, all of them, remain visible.
On the other hand, it has brought the main content part far to the left, overlapping with the sidebar content. This is because the sidebar div is not part of the normal page element flow. You have specified the width of the sidebar div, with the grid classes col-sm-3 and col-md-2, but the actual position has been fixed, and, hence, this element is not taken into account when the browser positions the #main-content-container div.
How can you solve this problem? There is a very easy solution. All you have to say to Bootstrap is to align the contents of the row of the container to the right. You have learned how to do that with the help of the justify-content-* classes and, in particular, with the class justify-content-end.

Dashboard with Main Content Justified End
The last problem that remains to be sorted out is the fact that the left-side navigation bar does not extend to the bottom of the window. This is expected because you have turned the sidebar div into a positioned element with position fixed. Positioned elements extend up to the necessary width and height according to the content they contain.

Left Sidebar with Full Height
Perfect! The left sidebar now occupies the whole height. Try scrolling and changing display widths. You will see that everything works as expected.

Task—Admin Dashboard (Top Part of the Page)

Task—Admin Dashboard (Bottom Part of the Page)
You need to use the font family Anonymous Pro. Look at Google Fonts for that.
Should not extend its height to be equal to the maximum height available
Should have transparent background color
Should have a color #eee border, solid and 1px all around it
Should have its border radius be 2px
Should have its position be fixed even if we scroll the main content area
Should have the position be left 10px and top 70px
Should have the dashboard area be composed of 300 × 300 image placeholders
Note If you want to generate such placeholders, visit https://placehold.it and learn how you can generate one. For example, you can visit https://placehold.it/450x450, and you will get an image placeholder with the requested 450px × 450px dimensions. You can right-click and select Save Image in order to save that as an image file in your computer, for later use in your site.

One Information Container per Row on Extrasmall Devices

Two Information Containers per Row on Medium Devices

Three Information Containers per Row on Large Devices
Otherwise, the exercise is similar to the work described in the chapter.
How you can have a top navigation bar with a search form inside
How you can have a side navigation bar that is sticky
How to hide parts of a page on small devices
How to create circle-shaped images
How to align content and make an admin dashboard
How to create responsive tables
Lots of other details and techniques to tune the layout of your page
In the following chapter, you will build stunning forms with Twitter Bootstrap.
You have already learned about the HTML forms and each one of the form controls. Twitter Bootstrap gives you some extra tools in your hands, in the form of classes, that will allow you to style your forms very easily.

Sign In Form Example

Sign Up Form Example

Sign Up Form with an Error
Learn how to implement Twitter Bootstrap basic forms.
Learn about the Twitter Bootstrap horizontal forms.
Learn how the horizontal form uses the grid classes to lay out the labels and the input controls to different columns but on the same row.
Learn about Twitter Bootstrap inline forms.
Learn how you can display help text below an input control.
Learn about read-only controls.
Learn how you can display select boxes using Twitter Bootstrap.
Learn about the validations.
Learn how you can change the size of input controls.
Learn how you can group two controls together and create an input group.
Twitter Bootstrap offers a series of classes that affect how forms and form controls are styled. In this chapter, you will design a Twitter Bootstrap Forms Reference page, in which you will lay out all the major facilities Twitter Bootstrap offers you with regard to this subject.
Let's start.
Save the preceding HTML content in the index.html file. Also, prepare an empty stylesheets/main.css file that will store your CSS rules. If you save those files and load the page on your browser, you will not see anything, because the body does not contain any content.
The intention is to add the whole content of your page inside a container div. That's why you can see inside the body the div with the class container.
As you can read in the preceding code, you are going to create, initially, a two-column layout. The right column is empty, for the time being. The left column contains a header h3 and a small paragraph p. But the important stuff here is the form element.
This is a simple form element without any class attached to it. This is the basic form style that Twitter Bootstrap offers.
Labels and inputs are grouped together in div. Each div has the class form-group. However, there is an exception for the checkbox-related div. It does not have this class. I will explain why in a while.
Each input control has the class form-control, except for the checkbox input, which has the class form-check-input.
You use the flexbox-related classes justify-content-between and align-items-center in order to position the checkbox and the login button on the same row. More explanation will be provided in the following.
The class form-check is used on a div that includes a checkbox.
The class form-check-label is used on the label that accompanies a checkbox.
Otherwise, anything else on the preceding code is pretty straightforward and does not use anything new.

Sign In Form

Input highlighted when it gets the focus
The class form-group does something very simple. It adds a bottom margin of value 1rem. Hence, it is useful if you have a vertical form, like in the example, in which the input and their labels flow in the vertical direction.
The class form-check has been used for the input and label that have to do with the checkbox. The most important rule this class applies is a left padding of value 1.25rem. This makes the checkbox align left nicely with the other elements of the form in the vertical direction. You can, if you want, apply the form-group class too, especially if other controls follow below your first checkbox.
The class form-control is very important to be attached to the input elements. It takes care of width, height, color, background color, borders, and other styling properties.
However, don’t use this class (form-control) for the inputs of the type checkbox. These are completely different visual-wise. They need to be given their own specially designed class named form-check-input. This class gives position absolute to the checkbox input, with no specific coordinates. Hence, it is drawn relative to its nearest positioned1 ancestor. Since you are putting the input inside a div with the class form-check, it is absolutely positioned relative to that div.
Labels do not take any special class, except for the label that accompanies a checkbox input. This needs to have the class form-check-label. It eliminates the bottom margin. This aligns it better with the actual input.
The class d-flex that is attached on the div that contains the checkbox and the login button turns the div into a flexbox container. This means that it lays out its elements in a row direction. If you temporarily remove it, you will see the login button appearing below the checkbox input.
The class justify-content-between takes the two child elements of the flexbox div and aligns them in the row direction so that they have blank space in between. Hence, one child is aligned left, and the other is aligned right.
The class align-items-center aligns the children of a flex div but on the non-main axis direction. The default main axis is row (x, horizontal). Hence, the align-items-* class aligns the children in the column (y, vertical) axis direction. This particular one aligns them centrally.
The previous form had one row for the label and a separate row, below the label, for the input control. You have the alternative here to implement a horizontal form . This form has the label and the input control on the same row, occupying adjacent columns. The HTML markup is more complex and uses grid-related classes. Let’s see how.

Horizontal Form on the Right Column
Each form group (div with class form-group) now has an additional class row. This will allow us to use the grid feature of Bootstrap to lay out the children within each group.
The two labels, for email and password, occupy a two-column width. That’s why they have col-lg-2. Note that they also need to have the class col-form-label. This class is specially designed to align the label vertically.
The two inputs, for email and password, are wrapped into a div with class col-lg-10, which makes them occupy the rest of the available horizontal space.
The row that contains the checkbox occupies a column width of ten, right aligned. This happens with the help of the class justify-content-end, which justifies the children of the div to the right of the flex container, and the help of the class col-lg-10 at the inner div, which makes the div occupy ten columns.
Finally, notice how we create the help text below the email input. It is done with a small element that has the classes form-text and text-muted.

Inline Form Example

Bootstrap Inline Form, at the Bottom
The form tag needs to have the class form-inline. And this makes the whole difference. Otherwise, no form-related classes have been added other than the ones you already know. You have only used some margin utility classes, such as the class mr-sm-2. The only thing that these classes do is to add some margin in order to make the elements of the form have some free space around them.
There are many times that an input control requires the user to enter a piece of information that is not very common. The UI needs to make sure that the user understands what they have to key in. The label helps. The placeholder helps too. But there are times that an extra hand of help is needed, in order to offer a more detailed explanation. In that case, you might want to use the tool that is called Help Text .
The help text, usually, appears below the input control; and it is a phrase explaining to the user what they have to key in.
You add a page header with title Other Form Elements. This is pretty much done with an h3 element with some top margin (class mt-4) and an hr element with some vertical margin (class my-4).
You are introducing a new form on your page. This will be a horizontal form and will be used to enclose a series of form elements that I would like to talk to you about.
Start with the Help Text. This is implemented with a simple small element that has the classes form-text and text-muted. It is positioned exactly after the input control that it accompanies. Other than that, there is nothing special to the preceding piece of code.

Start of the Other Form Elements Part of the Page

Input Control as Read-Only Plain Text
Do you see? The email input with value foo@bar.com has been styled so that it does not look like a normal input control. This is done with the help of the class form-control-plaintext. Otherwise, all the rest of the HTML markup is as you know it.

Page Part with Select Boxes
The class form-control styles the select boxes, similarly to the styling that other input controls get with this class.
There are many times that one wants to highlight the input controls that have been given erroneous input by the user. Or one may want to highlight the ones that had correct input. One way to do that is by coloring the input controls accordingly, for example, the erroneous inputs with red color.
is-valid
is-invalid
valid-feedback
invalid-feedback
You attach the class is-valid or is-invalid to the input you want to style as valid or invalid, respectively.
You attach the valid-feedback and invalid-feedback classes onto a div that holds a feedback message, for valid and invalid cases, respectively. This div needs to exist exactly below the input element, as the first direct sibling.

Input Validation
Do you see how valid and invalid inputs are styled? With the help of a small bunch of classes, Bootstrap allows you to do amazing work on styling.

Different Input Control Sizes

Different Input Control Sizes with Some Input

Input Group Example

Decimals Input Group Example

Dollars and Decimals Input Group Example

Label and Input Control Grouped Together
Combining these two (and, on the third example, three) controls into one is called input grouping.

Input Groups
The input-group needs to be a div with class input-group.
The div needs to contain the input element. It is the place where the user will input their username, in our example.
The visual adornment is before the actual input. Hence, the input needs to be prepended with a div that has the class input-group-prepend.
This div, with class input-group-prepend, needs to have the adornment inside a span with class input-group-text.
Very easy!
If the visual adornment needs to go after the input element, then its div class needs to be written after the input element, and its class needs to be input-group-append (instead of input-group-prepend).
You can have two visual adornments—one before and one after the main input control. You just use one div with class input-group-prepend before the main input control and another one with class input-group-append after it.
Make special provision for checkboxes and radio buttons inside the prepend or append part of the group. They should not be wrapped in a span, but they should be wrapped in a div.

Input and Button Group
As you can see in the HTML code, the implementation is quite similar to the previous cases. The only difference is that you don’t wrap the button inside any span or div with class input-group-text. You have the button as a direct and only child of the div with class input-group-prepend (or input-group-append).
You need to create one Twitter Bootstrap page with three forms on it.
The first form needs to be a sign in form like the following (Figure 8-21).

Task: Sign In Form
This is a basic Twitter Bootstrap form. The only difficulty that you may have is the symbol in the password input group. In order to add that, you will need to
Import/reference the FontAwesome library with fonts in your project. The FontAwesome project explains exactly how you can do that.
Add the HTML fragment that will represent the icon. It can be something like this:
This needs to be followed by a second form, the sign up form, like the following (Figure 8-22).

Task: Sign Up Form
Nothing is new here. Make sure that you use the correct FontAwesome icons for the passwords and the name fields.
Pay attention that the input controls are large.
The third form is the same as the second one, but all the input fields have been marked as valid or invalid. In fact, all are valid except for the password confirmation which is invalid (Figure 8-23).

Task: Sign Up Form with Validations
Note that on this third form, all input fields are populated with a value. You have to do that. Hint: Set the value attribute of the input HTML element.
Also, the red message “It does not match your password” is an invalid feedback. This needs to be a div element exactly next to the input control it accompanies, that is, the password confirmation input control.
How to create stunning forms
How to lay out the form inputs horizontally and vertically
How to group the label and the input field and style them together
How to group input with other visual adornments
How to make small and large input controls
How to display help text below the input controls
How to show validation success and error inputs
How to give validation feedback
How to style read-only input controls
In the next chapter, I proceed to more dynamic pages. You will learn how to create modal dialogs.
In this chapter, you start to apply JavaScript to Twitter Bootstrap. You will see how Bootstrap provides very useful JavaScript libraries to help you add dynamic behavior to your web application, with as little effort as possible.

Modal Dialog Example
Then I explain how you integrate Twitter Bootstrap JavaScript libraries with your own HTML page.

Example Modal with Pictures

Modal with Two Cities to Choose from
Learn about modals.
Learn how to reference the Twitter Bootstrap JavaScript files.
Learn about the bare-minimum HTML markup that introduces the modal functionality.
Learn which Twitter Bootstrap classes have to do with the modal functionality.
Learn about the main parts of the Twitter Bootstrap HTML markup.
Learn how data attributes can be used to trigger a modal.
Learn how you can program a button to open a modal when clicked.
Learn how you can have a close [X] button in the top-right corner of the modal.
Learn how you can use FontAwesome as an icon for the close button.
Learn how you can display images on the modals.
Learn how you can display YouTube videos on the modals.
Learn how you can display other/external pages on the modals.
Learn how you can display large and small modals.
Learn how you can use the Twitter Bootstrap grid system inside the modal body.
Learn how to activate modals using JavaScript.
Learn how you can customize modal behavior by setting various options using JavaScript.
Learn about the various modal methods available.
Learn about the various modal events that you can hook event handlers on.
Users can read the information and then close the modal. A modal can have a Close button or a [X] button in the top-right corner that closes it.
Users can fill in some form and then click the submit button of the form. This usually closes the modal and returns the user back to the main page.
Twitter Bootstrap offers modals for free, as part of the JavaScript integration. Let's see how.
In order to be able to use modals, you will need to reference the Twitter Bootstrap JavaScript files . These need to be referenced after the jQuery JavaScript files.

Correct Order of Loading External JavaScript Libraries
As you can see in Figure 9-5, I am using a reference to a CDN version of the Twitter Bootstrap JavaScript file. And I load it after the jQuery and Popper files, because Twitter Bootstrap JavaScript relies on jQuery and Popper.

Custom JavaScript File Correct Position
If you save and load the page on your browser, you will see a blank page. This is because the modal is not meant to be displayed, unless the user chooses to do so or they carry out an action that triggers the display of the modal.
The classes that make the modal content invisible are the classes modal and fade. The modal adds a display:none; and the fade adds an opacity: 0.

Disabling Properties to Reveal the Modal

Main Parts of the Modal HTML Markup
A div with classes modal and fade
A div inside the previous one (the one with class modal fade) with class modal-dialog
A div inside the previous one (the one with class modal-dialog) with class modal-content
A div for the modal header with class modal-header
A div for the modal body with class modal-body
A div for the modal footer with class modal-footer
Note that these last three parts are optional. Also, inside them, you can put (almost) any HTML markup that you like.
Modals are hidden until the user takes an action that would display them or until the web application decides that it has to display them. How does this trigger take place?
Add the preceding markup exactly before the modal starting div, below the <body> opening tag.

Page with a Button to Open the Modal

Modal Displayed After Clicking the Button
Perfect! This is what a modal is.
It has the attribute data-toggle with value modal. This is necessary to indicate to Bootstrap that this is a button that, when clicked, will open a modal dialog.
It has the attribute data-target which has a value being a CSS selector and needs to uniquely select the HTML element that holds the modal HTML markup. In the modal you are developing, you have used the value modal, because this is the class that uniquely matches the div holding your modal markup. Usually, here, you use a CSS selector that represents an id, rather than a class, in order to make the identification unique and avoid ambiguities.
Note that with this little HTML markup and using the data attributes that are identified by Twitter Bootstrap, you have managed to add dynamic behavior to your page. You didn't have to write any JavaScript. All this modal JavaScript functionality has been provided by the Twitter Bootstrap JavaScript library.
Besides the standard HTML modal markup that I have talked about before, there are some other elements on the previous example that deserve your attention (Figure 9-11).

The [x] Button
It is a button of class close with the data attribute data-dismiss equal to modal, instructing Twitter Bootstrap to close the modal if clicked. The actual icon appearing there is the <span aria-hidden="true">×</span>. The × entity element is a special character displayed as the cross [x].

A FontAwesome Icon Is Used as the Modal Close Button
Creating an account on FontAwesome is quite easy. You visit the page https://fontawesome.com, and you sign up. Then you need to create a kit. The site will give you directions on how to get your kit identifier in order to reference/use it in your HTML page.
Again, the important thing is that it has the data attribute data-dismiss equal to modal which makes it function as a modal close button.
The Save changes is a button that does nothing. I have not attached a functionality to it.
If you read the HTML, you will see that the modal-body div contains only an img element.

Modal with the img Element—Problem with Wide Images

Image Displayed Correctly Inside the Modal
As you can read in the preceding code, you can embed a YouTube video with the use of an iframe element. Make sure that width is set to 100% and height to reasonable height that will keep your video displaying with the correct aspect ratio. Note that YouTube gives you the code for the iframe element, when you choose to share a video via embedding. You only have to tune the width and height attributes so that the video is displayed nicely inside your modal.

Modal with a YouTube Video
Extralarge modals: You need to append the class modal-xl next to the modal-dialog class. It basically sets the modal max-width to 1140px.
Large modals: You need to append the class modal-lg next to the modal-dialog class. It sets the max-width to 800px.
Small modals: You need to append the class modal-sm next to the modal-dialog class. It sets the max-width to 300px.
If you don’t specify any of the preceding size classes, then the default sets the max-width to 500px.

Large Modal Demo
If you have noticed, when you open the modal, it animates from top to bottom. You can remove this animation and make the modal appear at once, by removing the class fade from the top-level div container.
Try that by removing the fade class from the previous example. You will see the modal appearing without top fade in animation.
You can use the Twitter Bootstrap grid system inside the body of the modal. Use container-fluid and then row and column-xx-x classes appropriately inside the modal-body div container.

Grid System Used Inside the Modal Body
The default behavior of the modal is to appear at the top side of the page. If you want to make the modal appear in the middle, that is, vertically aligned, then you have to attach the class modal-dialog-centered next to the modal-dialog class.

Modal Vertically Centered
As you can see, the modal appears vertically centered.
The important bits here are data-toggle="modal" and data-target=".modal".
It references a JavaScript file with custom JavaScript code. The file is javascripts/open-dialog.js. See this reference at the bottom of the file, before the closing body tag.
The other one is that the button to open the modal does not have the modal-related data- attributes anymore.
Without giving you the open-dialog.js contents yet, if you save the preceding code, load the page on your browser, and try to open the dialog by clicking the button, nothing will happen.
If you save the preceding code inside the javascripts/open-dialog.js file and reload the page, then the modal dialog will open when you click the Open Modal button.
It is inside the implementation of the click handler for the button #open-modal-button. So, when you click this button, you call the modal() method of the Twitter Bootstrap JavaScript library. This is called on the selection of elements that match the $('.modal');, hence on the modal div container.
When calling the $(...).modal() method, then you can give a JavaScript object with options for the modal function. The options that you can give are the following:
backdrop : Boolean with default value true. It can also be a string with the value static. If you set the value to false, then the modal will open without a backdrop, and you will not be able to click outside of the modal in order to close it (Figure 9-19).

Modal Without Backdrop
If you set the backdrop value to static, then it will open the modal with a backdrop, but you will not be able to close the modal by clicking outside of the modal area.
keyboard : Boolean with default value true. When true, it closes the modal if you click the key <ESC>.
show : Boolean with default value true. It shows the modal when initialized. This is useful because you might want to initialize a modal without actually showing that until later. Change the JavaScript code inside the javascripts/open-dialog.js as follows (Listing 9-9).
This is not much different from the original version. But it is better because it splits the functionality in two. First, it initializes the modal; and then, when the button is clicked, it just shows it.
The initialization of a modal with modal({....}); and the show of an already initialized modal with the call modal('show'); fall into the category of modal methods. Let's see some more details about them.
Here is the list of modal methods:
.modal('show');
.modal('hide');
.modal('toggle');
It is used to hide an open modal or show a hidden modal.
You may already know that JavaScript programming involves a lot of event programming. Lots of JavaScript plugins out there define their custom events. Same goes for the Twitter Bootstrap modal.
show.bs.modal: This event fires immediately when the show method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event.
Let's do an example (Listing 9-10).
As you can see from the HTML markup, the modal-body of the modal dialog is empty. You are going to add content dynamically, using JavaScript, reacting to the show.bs.modal event. Also, the content that you will add will be related to the button that has triggered the opening of the modal. As you can see, there are three buttons that all open the modal dialog.
With regard to the JavaScript file content, I attach a handler on the show.bs.modal event for the modal (.modal) target. I also declare the argument event which will be holding the relatedTarget when the handler is called. I save the relatedTarget to $buttonClicked, and then I just use the .html() jQuery function to set the HTML content of the modal-body div. The modal-body div is selected using the jQuery method .find().

Page Modal When Clicking the First Button

Page Modal When Clicking the Second Button

Page Modal When Clicking the Third Button
shown.bs.modal : This event is fired when the modal has been made visible to the user and after all the fade transitions have been completed. If caused by a click, the clicked element is available as the relatedTarget property of the event.
hide.bs.modal : This event is fired immediately when the hide instance method has been called. This might be useful when you want to program some actions that need to be executed when the modal is being hidden.
hidden.bs.modal : This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).
The modal is shown.
Its backdrop is static.
A click outside the modal is performed or clicking an <ESC> key.
You need to implement a page in which the user picks up one of two favorite cities. In fact

Task—Page with a Button to Open the Modal and an Image Placeholder

Task—Modal with Cities to Choose from
Users should be able to click one of the images. When clicked, the modal should close, and the image selected should be displayed on the main page in the place of the placeholder.
You might want to have a custom CSS file. This will need to style the images inside the modal, as well as the central image on the main page.
Its responsibility will be to respond to the click performed on any of the two images in the modal dialog.
Close the modal.
Replace the src of the central image with the src attribute of the clicked image.
How to implement a modal dialog
The modal dialog parts, header, body, and footer
The backdrop of a modal
How to vertically center a modal
How to use the grid system inside the modal body
How to remove the fade effect on open
How to show an image inside the body of the modal
How to show a YouTube video inside the body of the modal
How to open small and large modals
How to customize the modal with its options
How to use the methods of the modal
How to attach to different modal events
In the following chapter, you will learn how to build a page with very long content, alongside a navigation bar whose active menu changes according to the content position on the window.
Long-content pages usually have top navigation bars that allow the user to quickly navigate to sections within the pages. This feature is accompanied by the fact that the menu item highlighted as active is automatically updated/changed according to the visible section of the page. ScrollSpy is a Twitter Bootstrap JavaScript plugin that, when used, automatically changes the highlighted menu item according to the position in the document.
In this chapter, you will learn how Twitter Bootstrap allows you to quickly incorporate such a feature in your long-content pages.
Learn how to add scrollspying functionality to your long-content pages.
Learn how you should set up your HTML markup to support scrollspying.
Learn how you can adjust the offset and activation point of the scroll sections.

Long Page with Top Navigation

Long Page with Visible Top Content

Content Covered by the Navigation Bar
As you can see, the start of the section that corresponds to the link you linked is covered by the navigation bar.

Content Is Not Covered when Clicking Menu Items

Clicking More Does Not Bring Content at the Top
In order to fix this, you will add some bottom margin to the body of your page.

Clicking More Brings Content at the Top

Menu Items Pointing to the Start Of Sections
The problem with the current page is that when you click a menu item and the content is scrolled to that point, the corresponding menu item does not become active. Also, the corresponding menu item does not become active if you just scroll the content from top to bottom, from section to section.
You need to tell ScrollSpy which element contains the content you want to spy. Usually, this is the body. You set the data attribute data-spy="scroll".
You need to tell ScrollSpy which is the navigation bar element that contains the list with the menu items. In your case, this is the div with id navbar. Hence, you have to add the data-target="#navbar" attribute to the body element.
You also need to set the position attribute of the body element to have the value relative .
Add the position: relative to the body element inside the stylesheets/main.css file.
Save all that stuff and reload the page on your browser. You will see that the first menu item is highlighted and then, when you scroll, according to the visible section of the page, the corresponding menu item is highlighted.
Sometimes, you may want the active section to appear highlighted on the menu, when the section start is earlier than the top of the page. For example, you may want to activate a section when the section start is 200px from top of page. You can do that with the data attribute data-offset which takes as value the number of pixels you want the section to be activated from.
Save and reload the page on your browser . Then start scrolling. You will see the sections being activated before the section start reaches the top of the page.
Your menu items point to ids corresponding to the start of the sections. See again the HTML fragment with the menu items in the navigation bar (Figure 10-7):
The beginnings of the sections need to have the corresponding/correct ids, for example:
When you save all files and reload the page on your browser, you will still see ScrollSpy working as before.
Note that you can also give offset property in the object that you literally construct and you pass to the scrollspy() method.
Create a long page to demonstrate the ScrollSpy functionality. Your page needs to have a top navigation menu that would move page content to the start of the corresponding sections. Create two versions—one that is using JavaScript and another that is using data attributes.
How to display a long-content page with a navigation bar
How to make the content visible and not hidden by the navigation bar
How to make the last section content appear at the top of the page
How to automatically change the active menu item as the user scrolls from top to bottom of the page
How to use either data attributes or JavaScript to activate ScrollSpy
In the last chapter of the book, you will learn about tooltips and popovers, a very appealing feature of a page, because it gives the user extra information about the elements they interact with.
Tooltips and popovers are great tools to embed extra, secondary useful information to the content of your page. This chapter teaches you both Twitter Bootstrap tooltips and popovers.

Example Tooltip Activated

Tooltip HTML Markup Treated As HTML—See Bold Text

Popover Example
Learn about tooltips.
Learn about activating tooltips and their opt-in feature.
Learn how to wrap a word or phrase into proper HTML in order to attach a tooltip to it.
Learn how to wrap a word or phrase into proper HTML, so that it stands out and a tooltip will appear when the user moves over it.
Learn about the tooltip options that can be used to customize its behavior.
Learn about popovers.
Learn about the differences and similarities between tooltips and popovers.
Learn about the options of the popovers.
Tooltips are a very nice way to display helpful text when a user hovers over a highlighted text. So it is used to give some extra useful information, like a tip or a hint.

Example Page with Tooltips on Specific Words

Tooltip Activated

RTF and quadcopter Do Not Have Tooltips Yet
Wrap the word into a span element. Hence, the word will not change its position with regard to the rest of the text.
Add the data attribute data-toggle="tooltip". This will tell Bootstrap that the content of the span will be decorated with a tooltip on mouse over.
Add the data attribute data-placement="top". This will tell Bootstrap that the tooltip needs to appear on top of the span content. Note that data-placement can take the value left, top, right, or bottom. Choose any value that best suits your case.
Add the attribute title having as value the text that you would like to appear on mouse over.
Activate the tooltips using JavaScript. This is necessary, because Bootstrap has tooltips not enabled by default. This is done for performance reasons. You have to opt in on each particular case you want tooltips in.
This, the preceding code, is the opt-in part of the implementation, which enables tooltips for all the elements that have the data attribute data-toggle="tooltip".
If you save all the preceding code and reload the page on your browser, everything will be ready. When you mouse over the words RTF and quadcopter , you will see the tooltips.
As you can see, the tooltips are displayed on mouse over.
There is a small improvement that we have to introduce. You need to find a way to tell the user that if they mouse over a particular word, a tooltip will appear with further explanation information. If you don't do that, then the user does not know that there is a tooltip hidden behind the word.
In order to achieve that, you usually want the word with the tooltip behind to be underlined with a dotted line. Twitter Bootstrap makes your styling work here easy. Instead of wrapping the text with the tooltip inside a span, you can wrap it inside an abbr element.
Go ahead and change the spans to abbr elements.

Tooltipped Words Are Displayed Underlined
animation : Has default value true. It applies a CSS fade transition when displaying the tooltip.
delay : This can be either a number or a JavaScript object. If it is a number, then it defines the delay, in milliseconds, to show or hide the tooltip. If it is an object, then it can have the show and hide properties with integer values representing the delay to show or hide, respectively.
html : This is a Boolean option that takes the value true or false. Its default value is false. With false, the value of the title attribute of the tooltip element is inserted using the .text() method. This means that even if the title contains HTML markup, this will not actually be used; it will be treated as plain text. On the other hand, if the html option is set to true, when you have a value on title that includes HTML markup, this will be inserted in the tooltip area using the .html() method , and, hence, the HTML markup will be respected. Let's see an example.
You have added <b>4 rotors</b> HTML markup inside the title.
Although it is not necessary when you set the html value to false, you will need the preceding snippet in a while.

HTML Markup Printed Verbatim

Tooltip HTML Markup Treated As HTML
As you can see, the HTML content of the title attribute is being displayed as an HTML fragment without problem.

Popover Example
Let's change the previous page that had tooltips on RTF and quadcopter words. You are going to put popovers.
This should be accompanied by the following stylesheets/main.css (Listing 11-4) and javascripts/main.js files (Listing 11-5).
This page is using FontAwesome again to draw the question mark icons next to the words RTF and quadcopter. In order to use FontAwesome, you have to create an account with them and generate an account-specific reference to their JavaScript library. You have to use this reference where the preceding code has the line <script src="https://kit.fontawesome.com/<your-font-awesome-account-public-key.js"crossorigin="anonymous"></script>.
data-toggle="popover". For tooltips, we use data-toggle="tooltip".
data-placement attribute is used for both to specify the placement of the element.
title attribute is used to specify the content of the tooltip. For popovers, this is used to specify the heading of the popover.
data-content is used only on popovers and specifies the content of the body of the popover.

Header and Body of the Popover
If you save the preceding files and load the page on your browser, you will be able to click the question mark icon in order to see the popover.
As you can experience, the way you have integrated popovers has the problem that the popover can close only if the user clicks the same hot spot it is used to show the popover.
You need to use the data attribute data-trigger="focus".
You need to add the attribute tabindex="0" for the first popover, tabindex="1" for the second, and so on.
Let's do these updates on the popovers of your page.
If you do these changes and you reload the page, then you will be able to close the popover by clicking anywhere on the page.
When you click to open a popover, you will see a blue border around the question mark icon, while the popover has the focus. You can get rid of it by applying the following CSS rule:
a[data-toggle=popover]:focus {outline: transparent;}
animation: Takes a Boolean value true or false. The default value is true. It applies CSS fade transition to the popover.
delay: This is either a number or an object. This works exactly like the delay option for the tooltips.
html: Boolean with default value false. If true, it allows the content to be parsed as HTML rather than plain text.
You need to develop a web page that demonstrates both the tooltips and the popovers.
Try to create a page like the following (for this page, the whole content has been taken from Wikipedia) (Figure 11-12).

Task Page with Tooltips and Popovers
How to create tooltips that appear when a user’s mouse moves over a special word or phrase
How to create popovers that appear when a user clicks an icon
Congratulations!
You are done with this practical encounter with Twitter Bootstrap! I really hope that you enjoyed this trip and you learned things that you can apply to your projects.