

has been working with software and software technology since the early 1980s, beginning with a Sinclair and taking his first steps as a programmer in BASIC and assembly language. He studied Information Technology at Humboldt University, Berlin, but left early, in the 1990s, to start his own company. He has worked with Internet technology and software development since the early days when CompuServe and FidoNet dominated. In 1998, he worked on one of the first commercial e-commerce solutions, and wrote his first book in Germany. Due to its wide success, he started working as a freelance consultant and author in order to share his experience and knowledge with others. He has written several books with Apress, Hanser, Addison Wesley, and other major publishers along with several self-published books—a total of over sixty titles. He also publishes articles in magazines and speaks at major conferences in Germany. Currently, Jörg works as an independent consultant, software developer, and author in Berlin. The main focus is web development (nowadays called full-stack), cloud native architectures, and web security. In his occasional spare time, Jörg enjoys reading thrillers and science fiction novels, and playing a round of golf.

is a freelance web professional based in India. Since 2015, she has been active in front-end development technologies including Bootstrap. She is particular in writing clean code.
Chrome > 45 | Firefox > 38 | Edge > 12 | Opera > 30 | Safari > 9 | |
Android | OK | OK | OK | Not possible | N/A |
iOS | OK | N/A | OK | Not possible | OK |
MacOS X | OK | OK | OK | OK | OK |
Windows | OK | OK | OK | OK | Not possible |
Generally, Bootstrap 4 is distributed using the official web site, https://getbootstrap.com and npm (node package manager). Moreover, you also can create your own distribution using the source code. Bootstrap utilizes the raw files of the cascading style sheets language Sass, a pre-compiler that translates into CSS (unlike the previous version, Bootstrap 3, where the primary language was LESS). All common packaging and building tools such as WebPack, SystemJS, or Browserify can be used without restrictions to add Bootstrap directly or from the sources to existing projects.
Bootstrap is also available via Bootstrap’s own content delivery network (CDN). A CDN enables a web site to frequently retrieve used public files from globally distributed servers. For example, when a user from the United States invokes your host in Germany, the CDN will ensure that the Bootstrap files are retrieved from a server in the United States. This relieves your server, the lines of the provider, and the Internet in general, resulting in a faster download for the user. Basically, this is a win–win situation. If you program on the intranet, a CDN is not to your advantage. If you expect only local users in Germany, there is no advantage to a CDN.
The JavaScript libraries are jQuery for Browser abstraction and DOM access, Popper for notifications, and Bootstrap.js for all the interactive Bootstrap components. If you don’t use the components you can remove all three links. If you don’t use notification, simply remove Popper. The CSS parts are entirely autonomous and don’t need any JavaScript.
This book was reviewed with version 4.5.0. If you use a newer version, you will need to replace all the version numbers of the type 4.5.0 accordingly.
To obtain a local copy, you would usually use the node package manager, npm.1 Npm is both the repository for NodeJs and the tool to access the same. If you develop in Ruby on Rails, you should look for the gem “Bootstrap for Sass.”2 Other environments may come with their own package repositories, but because Bootstrap is entirely for frontend development, a package manager from the JavaScript world is the best bet. Here, npm is the most important one. However, the code world is changing constantly and other providers arise all the time, so keep an eye out for new sites for download or public repositories.
The files are now in the folder node_modules of your local project. This gets referenced by whatever development tool you use. Either you add the paths to index.html or another start file manually, or let a packer do this. (Packers are beyond the scope of this book, so you need to do your own research.) The example files provided in the Github repository for this book don’t use any such dependencies, and use the manual integration instead. This simplifies the setup for beginners.
scss: Path to Bootstrap’s Sass source files
js: Path to Bootstrap’s JavaScript source files
dist: Path to Bootstrap’s minimized CSS and JS that has been precompiled
Bootstrap was developed in version 4 with Sass.3 Sass is available on all platforms. Bootstrap uses Autoprefixer to work with the vendor prefixes in CSS. If you want to compile Bootstrap by using the Sass source and not use the supplied Gruntfile, you must use an Autoprefixer integrated into your own build process. If you use the precompiled Bootstrap files or the Gruntfile, the prefixes are already integrated. The procedure applies to Gulp and other taskRunners equivalent if they are to be used. The appendix reviews this in more depth.
Bootstrap can be downloaded in two types of packages: the compiled version and additionally minimized variants.
Precompiled files are the easiest way to use Bootstrap. The min versions are additionally minimized (compressed). The map files support the developer tools in the browser by mapping the sources to the distributed codes. They are not supposed to be deployed to production environments.
If you have a Minimizer (sometimes called Minifier or Uglifier) in your project, you pass the nonminimized files (the ones without “.min.” infix). Some minimizers destroy the code if it has already been compressed by another minimizer.
In addition to CSS and JavaScript, your app may require fonts that provide the icons. Font symbols are a particularly compact and simple method to incorporate monochrome icons in web sites. Bootstrap 4 does not bundle anything here, and you need to add a font package by yourself. One well- known package is FontAwesome (more on this in Chapter 6, where various icon options are presented). For now, just note that an additional installation step required.
The first two metatags from line 5 must be at the beginning of the block.
If you load this page locally via file:///, consider that some parts may not work as expected. Always try to carry out all stages of development with a local web server (IIS express with Visual Studio, IIS, NodeJs, or a local Apache or nginx are perfect for this).
Note that Bootstrap itself must be loaded after jQuery.
Download only from a CDN when your web site will be public. For an intranet, a local copy is more suitable.
Even with Bootstrap 4, browser support remains an issue. It has been taken a good deal of effort to reach as many browsers and platforms as it does. Currently it looks like this:
Chromium and Chrome for Linux and Firefox for Linux should work, but are not officially supported. The broadest coverage with browsers you currently have is with MacOS and Windows. Internet Explorer is no longer an option in any version, but officially there is support for version 10/11. However, this support will be dropped with Bootstrap 5.
Support for barrier-free applications (Accessible Rich Internet Applications Suite = ARIA )4 is actually an HTML topic. Some examples in the text are already geared and carry these attributes. Here is an overview of how this works. Bootstrap supports ARIA implicitly and comprehensively.
Bootstrap’s code makes use of several of these ARIA tags and attributes. Even if you don’t have any intention of using it, it makes sense to understand something about Bootstrap’s internal settings.
The role-attribute is set in the relevant HTML tags. It improves semantic markup and thus helps screen readers and other devices to present the correct output. It’s part of the effort to help advanced screen readers to render properly and make use of distinct local resources. There is a complete description available online.5
For example, imagine a device that has a hardware “search” button. On your page are two forms. One is for searching your site, one for sending a contact form. With <form role="search"> the device would be able to link the right form to the hardware button, making your page appear a lot more professionally designed.
banner: The element is a banner
complementary : The element adds a section, usually instead of an <aside>
content: Regular content
info: Additional information
form: Form
main: Main area
navigation: Navigation area
search: Search
article: Article (text)
columnheader: Column header
definition: Definition
directory: Directory
document: Document
group: Group
heading: Head area
img: Images
list: List
listitem: List item
math: Mathematical formula
note: Note, or supplement
presentation: Presentation, display support
region: Area
row: Row
rowheader: Head of a row (left turn)
separator: Separation line in menus or lists
toolbar: Toolbar
In addition to the barrier-free access, ARIA facilitates semantic attributes that take care and help the maintenance of your pages source code. It is always easier to work with role="banner" compared to work interspersed with dozens of <div> elements.
This list requires about 530 characters in UTF-16 that are more than 1 KB (in UTF-8 only the characters outside of ASCII have several characters). When you view 40 items on the page, which is not usually a problem because of the drop-downs, there are 40 KB HTML and a payload of roughly 2 KB (40 times the text for each entry with 50 bytes). Here it is worthwhile to use JavaScript.
The script will only cost about 250 bytes (130 characters without the comments). Instead of a maximum of 40 KB, this solution requires less than 2.5 KB: if you want it to look more striking, it’s 6% of the original size or a decrease of 94%. In addition, the JavaScript code can be outsourced and cached in the browser.
The script can be further refined so that the switching times only appear when the mouse pointer hovers over the entry. The append is only performed when a mouseenter emerges and mouseleave all buttons are removed. Ensure that events always in some $(document).on('click') pattern, so it works well with the dynamically appended elements. Tip: RTFM jQuery!
Why does this matter for Bootstrap? The smart structure of connected classes and the consequent usage of HTML may lead to many more elements and complex trees compared with pages written entirely manually. It clearly has advantages, and it will speed up your development time. But it will definitely come with a price. And if you want to refine your project, such techniques can be helpful. This is only one example of many such ways to improve performance.
This section gives an overview of the changes for those readers switching from Bootstrap 3.
The unit system has been changed from pixels (px) to rem (CSS) or em (Media Queries). The global font, which serves as the starting point, has been increased from 14 pixels to 16 pixels. This is mainly a reference to higher-resolution screens of mobile devices.
So far there have been four raster layers: xs, sm, md, and lg. In the future, there will be another level: xl. This is designed to support extremely large displays (3,000 x 2,000 pixels and more).
.table-inverse inverts the table
.thead-default and .thead-inverse format the header area
.table-sm creates smaller tables
All context classes now have the prefix .table-
.responsive-table can now be directly assigned to the table element, the container is no longer needed
.table-reflow supports reflow tables
Instead of the special class .form-horizontal, .row can now be used. All .control-- and .input--classes were unified to .form-control-. This means that the special classes .has-feedback and .help-block are obsolete.
The classes .btn-default and .btn-info have been omitted in favor of .btn-secondary. Another new feature is .btn-xx-outline—a bezel button. The class .btn-xs is removed.
Instead of <ul><li>-structures , these can now be formatted using <div><a>-blocks directly. These are the classes .dropdown-item and .dropdown-menu. The class .dropdown-header can now be applied directly to <h1> and the like. Intervals are created with </div class="dropdown-divider"> rather than the previous method, which used <li>-tags.
The display forms Wells, Panels, and Thumbnails have been deleted and replaced by a new component with the name Card.
Progress bar can now be created with the HTML element <progress>. Quotations need the class .blockquote. Due to lack of browser support, this has some limitations.
This chapter covered a short introduction to Bootstrap, ways to obtain it and add it to your web application, and some basics about the internal structure. The major changes from Bootstrap 3 to Bootstrap 4 were explained as well.
Before you begin to use Bootstrap, you should understand the basics of CSS (Cascading Style Sheets). Bootstrap is able to handle most of the obstacles and pitfalls of CSS. This means that a basic knowledge of CSS is enough for a beginner to handle Bootstrap-driven web sites. This chapter will give you a short introduction to CSS. It’s not my intention to provide you with in-depth coverage of CSS, as there are many resources available.
CSS is a layout and formatting language for creating and formatting markup languages such as HTML. Ideally, the HTML document contains only semantic information, and with CSS this is then formatted in design and typography.
HTML already provides some basic formatting, such as a larger font for headlines, which can then be customized with CSS. Almost all naturally unformatted elements can be changed in style and appearance by CSS, too. You should not use HTML’s formatting attributes to format HTML elements. Most of these attributes and pure formatting elements are obsolete in HTML 5, because the formatting capabilities are replaced by CSS entirely.
With CSS, it is also possible to define output types separately for different devices such as a monitor (screen), projector (projection), and printer (print).
An HTML document consists of semantically meaningful elements for headings, paragraphs, lists, and so forth. The CSS statements must be placed in such a way that the browser can assign styles to these elements.
The style attribute that applies to any HTML element, called inline styles.
The element <style></style>, which summarizes several styles, called internal CSS.
The <link /> element that references a file that contains multiple style definitions, called external CSS.
The preferred way to store these instructions is to use a separate CSS file. This file can be held in the browser cache and the content can be handled with the appropriate tools so that you can reduce bandwidth (not because of the bandwidth, but because of the associated performance gain). To make a file a CSS file, just add the file extension *.css.
Local <style> elements should be used only in exceptional cases, to temporarily change any complex styles loaded from files. Such local style instructions have a higher priority. The style-attribute expands or modifies the styles for a single element only. It has the highest priority over any conflicting rules from the local or imported styles.
Styles form a chain, managed by the priorities mentioned before. You can call it a cascade, too. And that’s the reason for the C in CSS: cascading.
The expansion or modification of the style-attribute is the way to let the browser understand how to load the file and treat it as CSS. Note that the path to the file must be specified relative to the HTML document.
Selector
Ruleset
When styles are in style attributes, they are only valid for that item, and therefore the selector is eliminated.
The semicolon at the end is mandatory.
The selector is the instrument that allows the elements on the page to be looked up selectively. The whole scheme of selectors is fairly comprehensive. Here, we’ll first cover the most important building blocks.
The ID must not begin with a digit. An underscore is allowed alternatively to any regular letter.
Frequently several elements are applied at the same time. To do this we use classes that are written in HTML in the class attribute. You can use multiple classes in the class attribute, divided by spaces, thereby combining rulesets in a smart way. This saves extensive definitions. Bootstrap utilizes this ability comprehensively and is able to achieve complex styling with only a few rulesets. A large number of modification options are available through class combinations. Unlike IDs, classes may occur more than once in a document.
Between a and b there is no link, so the rule is applied independently to both. The placeholders a and b in the example may be more complex selectors.
With the space between the elements, a child element is being addressed. Without, both classes must be used (like an AND operator). In this example, only the div elements “B” (line 12) and “C and D” (line 14) are properly formatted. The class “b” in <div class="a b"> can be omitted—it’s useless. If you change the ruleset .c.d into .c,.d (note the comma in the middle), the div elements “C” and “D” become green, too. The reason is that the comma is like an OR operator, so either the first or the second class definition is sufficient to fulfill the rule.
In practice, these selectors are not enough. The following table provides a compact overview of all the forms.
Selector | Description |
|---|---|
* | Universal/all |
tag | Element |
.class | Class (Attribute class) |
#id | ID (Attribute id) |
[a] | Attribute presence |
[a=v] | Attribute value |
[a~=v] | Attribute contains a value as a stand-alone word |
[a|=v] | Attribute contains no value |
[a^=v] | Attribute starts with value |
[a$=v] | Attribute ends with value |
[a*=v] | Attribute contains a value |

Elements of the hierarchy of a HTML page
Selector | Description |
|---|---|
|e > f | | Selection if f is a child element of e |
|e f | | Selection if f is a descendant of e |
|e + f | | Selection if f is a successor of e |
|e ~ f | | Selection when e is sibling of f |
In contrast to the possibilities of relationships, you might be missing the selectors for the ancestors, predecessors, and parents. You can often achieve this by swapping the elements.
Selector | Description |
|---|---|
::first-line | First line |
::first-letter | First letter |
::before | Before the element |
::after | After the element |
::selection | The highlighted (selected) area |
Selector | Description |
|---|---|
:root | Basic element |
:empty | Applies only if the element is empty |
:first-child | The first child element of a list |
:last-child | The last child element of a list |
:nth-child() | A particular child element of a list |
:nth-last-child() | A particular child element by the end of a list |
:only-child | Valid only when there is only one child element |
:first-of-type | First child element of a type |
:last-of-type | Last child element of a type |
:nth-of-type() | Child element of a type in a list |
:nth-last-of-type() | Child element of a type by the end of a list |
:only-of-type | Only this type from a list |
Selector | Description |
|---|---|
:link | A hyperlink |
:visited | A hyperlink that has already been visited |
:hover | A hyperlink with a hovering mouse |
:active | A hyperlink that is active (clicked) |
:focus | An item that has the focus (blinking cursor) |
:target | An item that has a target attribute |
:disabled | An item that is disabled (disabled attribute) |
:enabled | An item that is enabled (not disabled attribute) |
:checked | An item that is checked (only check box) |
:valid | An element that is valid |
:invalid | An element that is invalid |
:lang() | An item that the appropriate lang="" attribute is |
:not() | Negates the following selections (this is an operator) |
The examination of the validity of form elements presupposes that they were defined in HTML 5 using attributes such as maxlength, required, date, email, and so forth. For the most part, the change of these attributes applies to formatting only. The disabled attribute might be used to let an element appear disabled (grey, less shady, darker), but this might not prevent the element from being clicked. Often you’ll need additional JavaScript or change server-side rendering to achieve the intended effect.
Unlike the lang attribute, the function lang() in CSS can determine a fallback to a default culture, that is, responding to the indication of “en-US” on “en” and so on.
CSS units express length specifications. This is needed for widths, heights, spacing, margins, and so forth. Unit information consists syntactically from a number and a unit. For the number 0 the unit can be omitted. There are two types of units: absolute and relative.
cm: Centimeters
mm: Millimeters
in: Inches
px: Pixels
pt: Points
pc: Picas
Typographic units such as points and picas are holdovers from the era of paper printing. There you could define the exact widths when printing: 1 pica is 12 points, 1 point is 1/72 of an inch. In today’s world of screens with many sizes, widths and resolutions such information is largely pointless.
System | Resolution (pixels per inch) | Device pixels per pixel |
|---|---|---|
Mac | 72 | 1 |
Windows | 96 | 1 |
Mobil low | 120 | 1 |
Mobil medium | 160 | 2 |
Mobil high | 240 | 2 |
Retina | 300 | 3 |
This is rounded up to 316 and generally marketed as 320 dpi. Divided by 96 gives a ratio of 1:3.33, which is rounded as 3 device pixels per virtual pixel.
Generally, absolute data should be used only if the output can be determined with certainty. This is possible only in the case of printers.
If you need an absolute unit, you should resort to px when you use a screen. On a printer, you should mostly use mm or pt.
em: Unit of font size, based on the height in pixels (1 em is the size in pixels of the base font’s uppercase letter “M”)
ex: Unit of font size, based on the height of the lowercase letter “x”
ch: Unit of font size, based on the width of the digit “0”
rem: Unit of font size, based on the width of the lowercase letter “m” of the root element of the page (body)
vw: Relative to 1% of the width of the viewport (46 cm screen width is 1 vw = 0.46 cm)
vh: Relative to 1% of the height of the viewport
vmin: Relative to 1% of the width of the narrow side of the viewport
vmax: Relative to 1% of the width of the wide side of the viewport
%: Percentage to the original value
The unit em used in typography defines the size of the uppercase letter “M” as a measure of unity. This is not the case with CSS, where the value is comparable with the browser default font Times New Roman. Which concrete pixel value the browser uses is not clearly defined. The concrete pixel value is not 12 pixels as is often claimed, and even the more frequently encountered 16 pixels is not a guarantee.

Measurement of the pixels of the em unit
If you need a relative unit, you should use em or rem. The unit rem has the advantage in that it stays constant over the entire page, whereas em applies to the most current font.
HTML has two types of forms of representation for elements: flow and block. Flow elements embed themselves in the running text. These elements have dimensions such as width and height, for they depend on the surrounded content. On the other hand, block element dimensions cause adjacent elements to be displaced from their occupied space, and they can define the width and height they occupy by themselves. Moreover, the displacement behavior is highly customizable, up to the desired superposition. With special rules, elements that are actually floating elements are misidentified as block elements. This also can be reversed.

Blocks of the box-models
As there are differences between the paddings, border widths, and spacings, the calculation is accordingly complex. What’s graphically called a frame here is technically assigned as a “border,” assuming that the four sides are usually not exactly the same.
padding: The inner distance from content to border
border: The frame around the box
margin: The outer edge—distance from other elements
top
right
bottom
left
The coordinate origin begins at the top left of your screen or printed page. Some rules can be equal to specify multiple values. In such cases, the four values are interpreted in the order shown, starting with the top (upper left) and then continuing clockwise.
The margin that formed the horizontal distances is absolutely valid. The vertical distance, in contrast, may under certain circumstances coincide (collapse). This occurs when no frame (border) or spacing (padding) is used and no exemption (clear) takes place. Here the lower edge of the upper box is overlaid with the upper edge of the lower box. If there are edges of different size, the wider edge is taken as the whole edge.
There are a number of exceptions from the reunification rules of the edges. For more information, especially for complex pages, consult the official documentation on W3C Org’s CSS page.3
content-box: Data is only valid for the content. This is the default behavior.
padding-box: Information applies to the content and padding.
border-box: Information applies to content, padding, and frame.
inherit: Inherits the setting of its parent element.
The flexbox model (also known as the flexible box model, flexbox layout, or “flex layout”) was introduced to solve the challenge of aligning elements and distributing space in a container. The size of the available space is usually unknown or dynamic. The flexbox model gives great control for almost all possible layout options.
The properties supported by the flexbox model allow the modification of an item’s width, height, and order. We can define the behavior to use the available space even if the user changes the browser dimensions. Items can be shrinked and expanded to fill the space perfectly.
A layout based on flexbox model instructions is direction-agnostic. You can arrange the items based on different rules that apply if the available space changes or the application resizes.
Compared to the grid model layout, explained in the next section, the flexbox model provides better support for components based applications, were only few visible elements compete for space.
Container: A container is the space where the items are being arranged
Items: An item is a single element that takes space in the container
Both are controlled by a set of properties that CSS can apply. The actual element in HTML is not that important. While almost all examples use <div> elements, it is not limited to that.
Naming the class container has no meaning apart from documentation. Be aware that some frameworks may use the same technique inside and may also use such as class name.
row (default): left to right in ltr; right to left in rtl
row-reverse: right to left in ltr; left to right in rtl
column: same as row but top to bottom
column-reverse: same as row-reverse but bottom to top
nowrap (default): all flex items will be on one line
wrap: flex items will wrap onto multiple lines, from top to bottom
wrap-reverse: flex items will wrap onto multiple lines from bottom to top
flex-start (default): items are laid out to the start of the flex-direction.
flex-end: items are laid out to the end of the flex-direction.
start: items are laid out to the start of the writing-mode direction.
end: items are laid out to the end of the writing-mode direction.
left: items are laid out to left edge of the container, unless that doesn’t make sense with the flex-direction, then it behaves like start.
right : items are laid out to right edge of the container, unless that doesn’t make sense with the flex-direction, then it behaves like start.
center: items are centered along the line.
space-between: items are evenly distributed in the line; first item is on the start line, last item on the end line.
space-around: items are evenly distributed in the line with equal space around them. Visually the spaces aren’t necessarily equal, since all the items have equal space on both sides. The first and last item doesn’t have a predecessor or successort, hence the space is only one of the given units.
space-evenly : items are distributed so that the spacing between any two items (and the space at start and end) is equal.
You can also pair these values with two other keywords: safe and unsafe. Safe means here that you can’t render items in a way that they are off-screen to either side and would be no longer visible.
stretch (default): stretch to fill the container (this will respect min-width/max-width).
flex-start / start / self-start: items are placed at the start of the cross axis. The difference between these three keywords is subtle, and has to do with respecting the flex-direction rules or the writing-mode rules.
flex-end / end / self-end: items are placed at the end of the cross axis. The difference again is subtle and is about respecting flex-direction rules versus writing-mode rules.
center: items are centered in the cross axis.
baseline: items are aligned such as their baselines align.
Again, the safe and unsafe modifier keywords prevent content from being rendered invisible or not.
flex-start / start : items are laid out according to the start of the container. flex-start honors the flex-direction while start honors the writing-mode direction.
flex-end / end: items laid out to the end of the container. The (more support) flex-end honors the flex-direction while end honors the writing-mode direction.
center: items are centered in the container.
space-between: items are evenly distributed; the first line is at the start of the container while the last one is at the end.
space-around: items are evenly distributed with equal space around each line.
space-evenly : items are evenly distributed with equal space around them.
stretch (default): lines stretch to take up the remaining space.
The safe and unsafe modifier keywords can be used here as well.
Items are usually laid out by the containers options. In some cases it might be necessary to align single items differently. The few options CSS provides here are described as follows.
If flex-basis is set to 0; the extra space around content isn’t factored in. If set to auto, the extra space is distributed based on its flex-grow value.
The shorthand sets the other values intelligently. That makes it more robust and easier to use.
The grid model layout is the most powerful way to arrange items on the screen using pure CSS. It creates a two-dimensional system, using rows and columns. The flexbox model described earlier is more of a one-dimensional layout, with a single line that breaks at well-defined borders. In a two-dimensional layout you need to define a container (the grid container) and the containers items (grid items).
You can think of the grid model as an extremely powerful and flexible way to create tables.
Grid container: Made with the display: grid rule. It is the direct parent of all the grid items.
Grid item: The children (i.e., direct descendants) of the grid container.
Grid line: The dividing lines that make up the structure of the grid. They can be either vertical (“column grid lines”) or horizontal (“row grid lines”) and appear on either side of a row or column.
Grid track: The space between two adjacent grid lines. You can think of them like the columns or rows of the grid, that’s the space where the items reside.
Grid cell: The space between two adjacent rows and two adjacent column grid lines. Think of it as just a virtual space for an item.
Grid area: The total space surrounded by four grid lines. A grid area may be composed of any number of grid cells. It is like merging cells into a larger space.
grid: generates a block-level grid
inline-grid: generates an inline-level grid
This will create a grid that is four columns wide by three rows tall. The top row will be composed of the header area only. The middle row will be composed of two main areas, one empty cell, and one sidebar area. The bottom row is all footer.
The property grid-template is a shorthand for setting grid-template-rows, grid-template-columns, and grid-template-areas in one step.
According the other rules a property grid-gap exists, which is a shorthand for row-gap and column-gap properties.
start: aligns items to justify with the start edge of their cell
end: aligns items to justify with the end edge of their cell
center: aligns items in the center of their cell
stretch: fills the whole width of the cell (default)
start: aligns items to justify with the start edge of their cell
end: aligns items to justify with the end edge of their cell
center: aligns items in the center of their cell
stretch: fills the whole height of the cell (default)
This behavior can also be set on individual grid items using the align-self property. A place-items property exists to combine both, the align-items and justify-items properties in a single declaration as a shorthand.
start: aligns the grid to be justified with the start edge of the grid container
end: aligns the grid to be justified with the end edge of the grid container
center: aligns the grid in the center of the grid container
stretch: resizes the grid items to allow the grid to fill the full width of the grid container
space-around: places an even amount of space between each item, with half-sized spaces on the far ends
space-between: places an even amount of space between each item, with no space at the far ends
space-evenly: places an even amount of space between each item, including the far ends
This creates a 2 x 2 grid.
row: fill in each row by adding new rows as necessary (default)
column: fill in each column by adding new columns as necessary
dense: fill in holes earlier in the grid if smaller items come up later
dense changes only the visual order of your items and might cause them to appear out of order. That could raise issues with accessibility.
grid-column-start
grid-column-end
grid-row-start
grid-row-end
<line>: can be a number to refer to a numbered grid line, or a name to refer to a named grid line
span <number>: the item will span across the provided number of grid tracks (merge cells)
span <name>: the item will span across until it hits the next line with the provided name (merge cells)
auto: indicates auto-placement, an automatic span, or a default span of one
If no grid-column-end or grid-row-end is given, the item will span one track by default. Items can overlap if the placement enforces this. You can use the z-index rule to control their stacking order.
With CSS you may set the presentation of a document for different output media. Media queries are used to assign a style sheet to a medium. It’s called “query” because the output device is being asked for its type and capabilities in order to apply rules properly.
A media query list for criteria must meet an output medium so that a style sheet is included for processing. Media queries consist of a media type (e.g., screen or printer), a media characteristic (such as color capability), or a combination of both. By using the possibility of a combination, you can tailor a variety of output media style sheets.
Media queries cannot be quoted in style-attributes. You must use CSS files referenced using a <link /> element.
Specifying a media type is a simple keyword, for example, screen.
If no media query is specified or the specified query consists only of spaces, the default is all. The following shows a media query in a HTML document.
The print media type ensures that the style sheet printer.css is used only when printing. On the other hand, on a screen (screen) monitor.css is activated.
This procedure has the disadvantage that both style sheets often contain the same CSS rules. In addition, at least two files are needed.
The style sheet layout.css will apply when the display area of the output medium is at least 150 mm.
In this example, a style sheet is specified, which can be used both for print media type and the embossed media type.
This example shows how screens are assigned to a minimum 150 mm wide display area rules. A browser that understands media queries is ignoring the keyword only. By denying the query monochrome , the media that can deal with color can be utilized.
A special concern is one related to lengths units em or ex. In the processing of these values the default of the browser is assumed, which has been defined by the user (or his operating system). Normally em refers to the current font, which has not yet been defined at the level of the media query. More explanations about units can be found at the end of this chapter.
If you use features that relate to the display area, it is almost always a good idea to use one of the possible prefixes. The actual display width the user has cannot always be reliably predicted.
The feature height describes, in continuous media, the height of the display area (viewport) and paged media as the height of a page. The prefixes min- and max- are allowed to specify limits.
Even if an output device has certain dimensions, it says nothing about whether the available range is also used. Also, the measure of the pixels differ from the physical pixels—for example, this may be the case with retina displays. Likewise, for all devices that do not report their orientation, the value may not change. For Apple, the width stays the same in portrait mode—even if the user rotates the device and uses it in landscape format. Thus, you must be aware of orientation and test carefully.
In this example, the ratio value is assigned to the 4/3 variants of aspect-ratio-feature. The style sheet is processed if the aspect ratio of the display area (viewport) is exactly 4 to 3 equivalent (case 1). That is the case for example with a display area of 492 to 369 pixels. The style sheet in case 2 is applied if the aspect ratio is 4/3 or greater (e.g., 5/3 or 6/3). In case 3, the style sheet is processed accordingly only when the aspect ratio is 4/3 or less (for example, 2/3 or 1/3).
The feature device-aspect-ratio (the device’s aspect ratio) describes the ratio of the characteristic device-width to feature device-height. The application is similar to the feature aspect-ratio.
Support for color-index is currently deficient in all browsers.
dim: Dim lights
normal
washed: Bathed very bright, in light
fine: For devices with mouse, touchpad or stylus
coarse: For devices with touch or gesture control
none: Only keyboard input possible
With touch devices, the font size and the padding of the input field are increased accordingly.
Because most devices have multiple input options, their use can not be predicted. It is possible to use any-pointer to find out whether there is any input device at all.
You can use pointer and any-pointer if you are unsure of certain devices. However, you can ascertain this in combination with the display width whether someone is on the go via smartphone or tablet, or at home with a desktop computer. This allows you to optimize web pages for specific devices accurately.
The feature resolution describes the resolution, which is the density of the pixels on an output medium. If the output medium does not use rectangular pixels (for example, printers), the characteristic may be used only in conjunction with a prefix.
Among the foundations of development for mobile devices is the meta-element viewport . This one-line of HTML code ensures a correct scaling of the site on the first call of a device. This is especially useful for mobile devices, where the user’s ability to create a custom setting is somehow limited.
The browser of the mobile device goes to mobile view first, even if assuming that sites are not designed for it and the site-wide display width exceeds considerably the available space. The browser viewport (the display area) is therefore set, for example, in Mobile Safari to a width of 980 pixels, so that most sites are fully visible. This has the disadvantage that the content is very small, and fonts are illegible. The user must zoom in to see anything.

Web site with and without zoom
If the site is specifically created or optimized for mobile devices, you do not have to specify a fixed width for the viewport. For example, in portrait format a smartphone has a logical width of 320px, and 480px in landscape mode (physically, the value will be higher). This would mean that the same content would be shown only in a different zoom level in portrait and landscape modes.
The smartphone now has a width of 320px in portrait orientation, so precisely 320px on the site are shown (1:1 ratio). Likewise, 480px will then be shown in landscape orientation. This flexible approach is both device-independent and allows the landscape to have the extra space that makes sense in width.

View with and without meta-element
initial-scale: The value specifies the initial zoom level. A 1.0 means that the content of 1:1 will be shown. For example, on a screen with 320 px, a 320 px-wide graphics fills the entire width (see also the screenshot in Figure 2-3). Therefore, a 2.0 results in a 2 times magnification.
user-scalable: With this attribute, you can define whether the user can zoom in on the page (yes) or not (no).
minimum-scale and maximum-scale: These two properties you make it possible to limit the zoom level. Set the maximum scale to 2.0, the content can be increased maximum 2 times.
This chapter covered the basics of CSS and how the system of rules, selectors, and properties works. Because Bootstrap makes use of the flexbox grid models, the related rules are explained more thoroughly. However, the intention was to peek behind the curtain and not to give all details of CSS, because Bootstrap takes care of these details and obstacles for you.
Bootstrap constructs a horizontal grid on the page, and the elements are placed within. This is the fundamental part of the framework, and how to deal with the grid and its options is the first decision you make in your project.
The basis for the grid is a fixed allocation of the page. There are several options to distribute elements, centered or not, dealing with overflows and handling breakpoints for different screen resolutions.
A definitely requirement here is that the zoom behavior and the scale be used at the beginning. The zoom behavior can be turned off with user-scalable=no. The application then feels a little like a native app on a mobile device. shrink-to-fit is specific for Safari browsers on Apple devices (especially iPads), and helps to prevent the device from applying smart zooming, which usually makes things worse.
It is risky to switch off the zoom function. Users with limited eyesight or users of especially small screens may be reliant upon it. When a mobile web site needs to behave like a native app, it must also be built from the ground as an app.
In the early years of the Web there was an attempt to provide a kind of virtual grid to give structure to a page. Most often, tables were used. However, tables are rigid in their horizontal extension because the content determines the width. A scaling to a smaller screen is not possible.
The idea of the table shows the procedure, rather than simply having the cells take <div>-tags and then define these grid-like, using CSS. Anyone who has tried it may have quickly realized that the approach is anything but trivial. CSS frameworks therefore provide a solid foundation. In fact, the screen is divided into grids where the grid width can be adapted.
Containers of this type provide a solid, centered, and responsive grid. That is, the width adapts in the device’s viewport and then remains stable within a range. The effect is a jump to a new positioning once the range is left or reached. These jump areas are referred to as “breakpoints.” If you already know the concept of software development, note that the breakpoints in Bootstrap have nothing in common with this.
Extra small 576px | Small ≥576px | Medium ≥768px | Large ≥992px | Extra large ≥1200px | |
|---|---|---|---|---|---|
.container | 100% | 540px | 720px | 960px | 1140px |
.container-sm | 100% | 540px | 720px | 960px | 1140px |
.container-md | 100% | 100% | 720px | 960px | 1140px |
.container-lg | 100% | 100% | 100% | 960px | 1140px |
.container-xl | 100% | 100% | 100% | 100% | 1140px |
.container-fluid | 100% | 100% | 100% | 100% | 100% |
The grid is formed by twelve (12) equal width columns. Predefined classes can be used to place elements on a given column and span a number of columns at a time.
The elements are placed in the columns. Eventually the last column is reached, either by a number of elements or elements that span more than one column. The entirety is called a row. After that, a new row begins. Quite often you will control such rows without the need to fill up all columns. That’s why we use .row classes.
Rows (.row) must be in a container .container (fixed width) or .container-fluid (full width).
Rows may be used horizontally to place multiple elements side by side.
Columns (.col-xx-n) may be placed in rows. Only column elements are immediate child elements of rows.
Column spacing (gap between columns) are defined using padding-rules. These distances are to the left of the first column and the right of the last column with negative intervals (margin) balanced. This content is aligned outside of the grid left-aligned equal.
If the elements need columns that can be placed within a row and exceed the elements’ limit of twelve columns, then the whole group will be wrapped.
The name begins with col-
The middle part (infix) determines the jurisdiction for screen widths (xs, sm, md, lg)—the breakpoints. It can be omitted to get default behavior.
The number at the end determines the number of grid zones (1 to 12) the column spans.
If you use the class .col-xs-4 , you have three juxtaposing decorated elements (3 x 4 = 12). The higher (larger device) definition applies until it is overwritten. If you use class combinations such as col-md-2 col-lg-2, then “md” is not valid for very large devices.
“xs”: < 576px
“sm”: ≥ 576px and < 768px
“md”: ≥ 768px and < 992px
“lg”: ≥ 992px and < 1200px
“xl”: ≥ 1200px
Symbol | Device width | Container | Width |
|---|---|---|---|
xs | <576px | automatically | automatically |
sm | ≥576px | 750px | 62px |
md | ≥768px | 970px | 81px |
lg | ≥992px | 1170px | 97px |
xl | ≥1200px | 1570px | 112px |
The width of the spacing between columns is 30 pixels (15 on each side).

The grid system (desktop)

The grid system (mobile)
On a mobile device the same code produces the following screen:
It may happen that mobile devices provide adequate space, or represent some columns side by side. These are further definitions of .col-xs-- and .col-md--added classes.

Variable grid system (desktop)

Variable grid system (mobile)

Tablet (top) versus phone

Break off the grid

Normal container (top) and with -fluid (bottom)
In the following examples, I have dispensed with the container element to keep the code compact. But you must use a container element in practice.

Elements in moving columns

Behavior of nested columns

Sorting on a mobile device (lower part)
Some utility classes allow a finer control for element placement.
The class can be combined with any of the .col- classes shown earlier. .col-6 will cover six columns, and the .col class spans the remaining space and distributes equally in that space. The breakpoints apply, too. Just use classes such as .col-md, for example.
Sometimes you need more dynamics and want to stretch columns according to the content’s size. Here you can use .col-auto classes, whereas auto replaces the column number. All breakpoint infixes are available.
The responsive .row-cols- classes set the number of columns that best render your content and layout. Whereas normal .col- classes apply to the individual columns, the row columns classes are set on the parent .row. This is a simplification and reduces the number of <div> elements, but it doesn’t provide additional functionality.

Align in rows vertically
start: columns start left
center: columns are centered
end: columns align to the right
around: columns are around a center
between: columns are split to end and start (remaining content is between)
Note that the effect is invisible if all columns are occupied. The alignment makes sense if you have less than twelve columns in a grid of twelve ones. You may also have noticed that the terms “start” and “end” are used, and applies to “left” and “right.” In layouts with different writing direction order, “rtl” (right to left, such as Arabic) the “start” and “end” terms still apply. But “left” and “right” would be the opposite, which would be confusing.
Some helper classes are available to deal more directly with the grid, especially the flexbox model.
The classes in this realm do not completely replace the common flexbox rules. That wouldn’t make sense, as the options are many and the effort to learn new names contradicts the advantage of having a common style system. But for simple flexbox applications, it could be easier to use Bootstrap.
After creating a box using this, you can apply the row behavior using .flex-row. If you like to have a vertical flow, just use .flex-column or .flex-column-reverse. Even for these, the breakpoint infixes are applicable.
.flex-fill: stretch the items to fill the available space.
.flex-grow: let one element grow and the others remain in their natural size.
.flex-shrink: let one shrink as much as possible and the others remain in their natural size.
.flex-wrap and .flex-nowrap: control weather the elements wrap when reaching the box’ borders.
.order-{n}: change the items order with the number between 1 and 12.
This chapter covered the basic page layout, the grid, and the alignment of elements within. Some classes help to modify this layout, and you can also use common flex classes to create your own grid.
The background color of the page is white, background-color: #fff
$font-family-base
$font-size-base
$line-height-base
$link-color
Underline links should only be used with floating cursor (:hover)
The variables are in the file _scaffolding.sass and are easy to find.
h1: Bold 2.5 rem / 40 px (Basis × 2.6)
h2: Bold 2 rem / 32 px (Basis × 2.15)
h3: Bold 1.75 rem / 28 px (Basis × 1.7)
h4: Bold 1.5 rem / 24 px (Basis × 1.25)
h5: Bold 1.25 rem / 20 px (standard size, this is the basis for calculation)
h6: Bold 1 rem / 16 px (Basis × 0.85)

Standard view of headings
An alternative form of heading styles comes with the display classes. There are only four such heading styles. The class names are .display-1, .display-2, and so on. The font is slightly larger and the display headings stands a bit more out compared with the regular headings.

Display headings based on div
For text and text elements, HTML has many references and has class supplements for special effects.
The default font for the text is 16 px. The line height used is 1.15. Sections created with <p> will receive half the row height, about 10 px.

Paragraph style
<mark></mark>

Semantic elements in the text
<del></del>
<s></s>
<ins></ins>
<u></u>
<em></em>
Highlights part of the text with emphasis thereby showing its importance.
Another tag fits in this category, <small></small>, but it has a less important semantic reference. To achieve a lighter display you can reduce the font size to 85%. To do the opposite of this, you should use <strong></strong>.
Bootstrap supports the continued nonsemantic elements <b></b> and <i></i>. They react in the text similar to <strong></strong> and <em></em>. The element <i></i> is sometimes is used for icons, which do not contain text and therefore ignore the behavior displayed by italic font and enter an element with a certain semantic meaning. However, the behavior and the interpretation is not standard compliant, but more of a stylistic measure.
The <kbd></kbd> element is used to refer to keys of a computer keyboard (<kbd>F12</kbd>).

A properly formatted address

Left- and right-aligned quote

Display of variables or formulas
To explain sample output from a program you should use the element <samp></samp>.
text-left: left-aligned
text-center: text is centered
text-right: right-aligned
text-justify: justified
text-nowrap: obstruction of upheaval; in addition, there are alignment variants that are only valid for certain viewports.
text-xs-left: left-aligned when the viewport “xs” is used.
text-xs-center: text is centered when the viewport “xs” is used.
text-xs-right: right-aligned when the viewport “xs” is used.

Aligning text
Justified (justify) text on screens is generally not a good idea. If you feel the need for justification, remember that the width of the column can hold at least 10 words; otherwise, the spaces between the words become too large. Although justification does not work well, it can remain manageable by using artificial separations with the entity ­ (soft hyphen). The delimiters appear only if a break must be made.
text-lowercase: converts to lowercase.
text-uppercase: converts to uppercase.
text-capitalize: first letter of each word is capitalized.
text-weight-bold: bold without an explicit tag.
text-weight-normal: normal weight without an explicit tag.
text-italics: italics without an explicit tag.

Text transformation

Some styled lists

Assembly with two entries (vertically above, horizontally below)
It has been noted that tables are not suited to building responsive sites. Nevertheless, tables are suited for sorting and listing data. The width of the table must comply with the criteria of the grid. A placement outside of the grid is possible. In this case Bootstrap offers several styles to improve the presentation. For responsive environments, tables are offered with horizontal scrolling. Of course this is only a temporary solution; responsive tables should not need this.

A table that is partly condensed with header and footer
Tables also can have column definitions with <colgroup><col><col></colgroup> elements. However, those are not explicitly supported by Bootstrap.
.active: mouse effect for rows or cells.
.success: positive or success (green).
.info: information or action (blue).
.warning: warning or caution signal (orange).
.danger: negative or danger (red).

Table with column definitions
Note that even the column styles collide with .table-striped. Avoid .table-striped if your columns make color variations.
If a page is built accessibly, the context classes have no meaning. The potentially important information that arises from the choice of color is lost. Therefore, when you add additional items, you can mark these with .sr-only to make them invisible. Screen readers will still read these items.

An inverted table

A turned table

Table with scrollbar
You no longer need to apply .table-responsive as you did with Bootstrap 3 on a surrounding <div>- element.

A full-width table

A table at narrow width
The script checks for the header fields and creates an array (line 4). Then, it searches for the rows (line 6) and in each row the data-attribute of each element of the array is filled in (line 8).
The repeated declaration of data-title=“Code” is no longer necessary and can be removed completely.
The path shown in this section supplements the procedure in Bootstrap, but it is largely independent. The basic design and the distances were, however, taken from Bootstrap. You can use the scripting part without Bootstrap and add styles as needed.
Bootstrap includes a number of helper classes for general purposes.
The peculiarity of the distance classes is in the relation to the base font size 1rem. The data are therefore relative.
m: margin, the distance to the next element.
p: padding, the inner distance of the contents of the element frame.
t: set the property margin-top or padding-top.
b: set the property margin-bottom or padding-bottom.
l: set the property margin-left or padding-left.
r: set the property margin-right or padding-right.
x: set the property for *-left (left side) and *-right (right side).
y: set the property for *-top (above) and *-bottom (below).
auto: sets the property of all margin or padding rules for all four sides. The size will be determined as follows:
0: Sets all values to 0—no spaces
1: The smallest, $spacer * 0.25
2: $spacer * 0.5
3: The $spacer’s variable default value
4: $spacer * 1.5
5: $spacer * 3
The variables $spacer-x and $spacer-y are standard distance.
A special feature is the class .mx-auto, which sets the horizontal distance to auto, effectively centering an element horizontally.
This might have an impact on styles for header or footer parts. Carefully test all usage scenarios before relying on the full height definition.
The suffixes “sm” and “lg” refer to the size of the shadow, not the breakpoints. The shadows are traditionally aligned with the virtual light source in the upper left corner. Hence, the shadow is bigger on the right and bottom border. Be aware that the shadow adds additional space to the content area. If the next element comes quite close, this might need additional space or margin room. In that case, use the auxiliary classes shown in the preceding list.
The interesting part here is that the element itself does not appear bigger; only the clickable area grows. The button in the example remains small (following the content), while the container element will fill 50% of the available space.
Be warned that this could be irritating for users, but also quite convenient, depending on where you use it. Test carefully and let some common users give it a try before you officially release your app.
Some classes replace the common CSS. For example, the style="position:static" instruction could be written as class="position-static.” This applies to all position parameters. The intention is not to save you typing work (it is exactly the same number of characters). The reason is that the definitions can handle different behaviors of browser engines and allow refinements for other classes that need particular values. So even if there is absolutely no visible effect, it is strongly recommended to use such auxiliary classes instead of basic CSS or your own definitions.
The same goes for .fixed-top and .fixed-bottom, which are also quite simple. They fix an element and prevent it from scrolling with the whole page. If you want an element to scroll but also to stick if the element reaches the border (that is, with the next scroll step it would disappear), the class .sticky-top is your solution.
This chapter covered the basic aspects of typography in Bootstrap. While it is not difficult to use, an application’s fonts and styling have a tremendous effect on the overall appearance, look, and feel. The auxiliary classes are a common way to avoid using slightly different styles to apply minor corrections here and there. They make the basic styles themeable, which is important in real-life projects.
Forms are fully supported in Bootstrap 4. Many of the components are primarily used to make the forms responsive, and can be used with any screen width.
Form elements automatically receive the correct formatting. The main class for controls is .form-control. Elements that have controllable horizontal extensions such as <input>, <textarea>, and <select> are set to a width of 100% of the parent container. The labels and inputs are grouped using .formgroup. They arrange themselves depending on the available width, either side-by-side or one above the other.

A simple form
In addition to simple elements, more complex elements can be built out of simpler ones and then put together. This is then referred to as an input group. Element groups and group entries may not be used in mixed input groups, but instead should be nested as a child element.

A form with a horizontal orientation (wide)

A form with a horizontal orientation (narrow)
You should always use labels, even with one-line forms. Otherwise, screen readers cannot produce meaningful speech. Use .sr-only so the label will not appear on regular output devices. If an accessible output is required, the standard attributes aria-label or aria-labelledby should be used. While aria-label contains the text directly, it is referenced by arialabelledby="id" to the ID of another element on the page, which provides the label text.

A form without label
Input fields, especially those for text entry, can be supplemented for left or right text, icons, or buttons. This is particularly interesting when the values have units. Use the class .input-group with .input-group-append or .input-group-prepend to display elements before or after, using .formcontrol to create it. This works very well with all the <input>-elements and with limited success with <select>, but not with <textarea>.
The columns of the grid classes cannot mix with the input groups. Instead, the entire input group should be placed in a container if they are required, which in turn is provided with pitches.

Fields

Sizes of the input fields

Input fields with options

Input fields with buttons

Input fields with menus

Input fields with segment buttons

A form with no label

A form with a label next to the field
text
password
datetime
datetime-local
date
month
time
week
number
url
search
tel
color

Checkboxes and radio buttons

Checkboxes and radio buttons next to each other
Lists and drop-down menus can be used as usual. However, some browsers turn to internal styles that cannot be influenced with CSS. It could be that menus are a better choice to get full control over the design.

Static elements in horizontal layout

Static text in a form with horizontal layout

Locked elements (with mouse)

Elements in read-only mode
Bootstrap supports HTML 5 validation states. These are represented by the HTML 5 pseudoclasses such as :invalid or :valid. If it is not possible to use these for some reason, a fallback is available using the regular classes .is-invalid and .is-valid. The limitation to just two states, valid and invalid, is different from Bootstrap 3, where a third state, “warning” was available. If you need such states, use regular form elements with icons and semantic classes.

Semantic form elements

Semantic elements with ARIA support
The status shows with a color. Colorblind users may not benefit from this information. Therefore, the semantic meaning should always accompany the color information. This can be achieved by help texts, symbols, and .sr-only regions. elements that cannot be adapted should carry an aria-invalid=“true” attribute. Accessibility is handled widely by the ARIA standard (Accessible Rich Internet Applications), a W3C working draft published by the Web Applications Working Group. Examples that mention “ARIA” in this chapter refer to the related standardization documents.
As an option, use states with upgraded symbols. This can be accomplished with .valid-feedback or .invalid-feedback and a symbol on the right end of the message areas. These icons will only work if <input class=“form-control”> is used.
An additional font library is not required, and the styling shown is the default behavior. The JavaScript in the previous example is just to prevent the browser from reloading the page and invoke the validation process. The effect is shown in Figure 5-20. There is, however, no actual validation, and you must add custom code to have full validation support.

Semantic messages
The overlapping tooltip might require additional styling to justify the margins. This is an option if the space is somehow limited and dynamically visible error messages destroy the form’s layout.

Elements aligned with the grid

Elements in various sizes

Elements aligned

Help texts
Use any of the .text-* classes to style the help text according to your needs.

Buttons—several variants of the same effect
However, there is one restriction: in navigation bars built with .nav or .navbar, only the common element <button> is allowed.
If <a> tags are used as a button, they should only serve the navigation and not trigger as a hyperlink, because this is not the expected behavior. Moreover, it should be emphasized by the attribute role=“button.” Even then it is questionable whether this is a good idea, as not all browsers can ensure that the function will behave as expected. So take advantage of the distinct buttons and whenever possible, it is preferable to use <button>.
Primary: raises the main function, visual effect by blue color amplified.
Secondary: standard, gray, general function.
Success: success, green, positive, or affirmative action.
Info: information, azure, clarified highlighting critical or special actions.
Warning: warning, orange, critical or complex action, should be taken with caution.
Danger: danger, red, dangerous or irreversible action, negative.
Link: formats a button as a link, often referred to as reduced action, additional behavior.

Semantic buttons
Assigning semantic meanings on the color labels may be restricted by size in some environments. Additional labels, which are equipped with .sr-only, should emphasize the intended effect.

Size of the buttons

Buttons horizontally expanded

Semantic buttons with frame

Various states of a button
Note that the cut-off of elements with CSS classes is merely cosmetic. This is also the case with pointer-events: even if there are none internally, this does not prevent those elements from being selected with the keyboard, and they can still trigger actions. You need to check with JavaScript that the function will coincide with the presentation.
This chapter examined the basic ways to style forms. Apart from the default behavior, Bootstrap adds to any form the validation response based on the attributes defined by HTML 5. In this chapter you also got an idea what semantic styling is about and how to use it for fields and buttons.
This chapter is about images, effects, and symbols. The only images supported are some effects that are available here.
The symbols—font-based icons—are the basis of the icon functions. The glyphs used in Bootstrap 3 are called Halflings (a reference to Lord of the Rings) and are usually not free. Bootstrap 4 no longer contains the Glyphicons, and you have to use one of the many font libraries.
Font-based icons avoid the problem of individual symbols leading to a flood of additional requests on the server. Instead, all the symbols are loaded as a font—that is, in one file. However, the symbol is then like a letter. It is changeable in size and extent, but it may take only one color. Fonts are also mainly flat; 3D effects are eliminated. For fast, modern web sites, so-called glyph fonts are an established technology.
Font Awesome (http://fortawesome.github.io/Font-Awesome/)— number depends on license and package
Feather (https://feathericons.com/)—282 icons (2020)
Octicons, the Github Icons (https://octicons.github.com/)—160 symbols
Elegant Icon Font (http://www.elegantthemes.com/blog/resources/elegant-icon-font)—360 symbols
Typicons (http://typicons.com/—336 symbols
Meteocons (http://www.alessioatzeni.com/meteocons)—40+ weather symbols
Open Iconic (https://useiconic.com/open)—223 symbols, which can be up to 8 px down

The free symbol font Octicons (MIT license from Github, Inc.)
This is only a small selection, and provided here to encourage you to seek the right support before your first design experiments. The first three are recommended by Bootstrap, but the decision on which icons to use is up to you. Consider the icon set’s style, license (free or paid), and your personal preferences.
The CSS file contains references by URLs to the actual font files. You must add these files to your deployment package. In web sites with static files, that means you copy the font files from node_modules to the destination folder. Fonts come usually in different versions to support any number of browsers. However, these days almost all devices support *.woff2 files. It’s probably enough to copy just these. Other formats are *.ttf (TrueType), *.svg (Scalable Vector Graphics), *.woff, and *.eot. While copying too much may not really harm your apps performance, other techniques might suffer. If you use WebPack and pack the files into the bundle, the bundle will increase dramatically in size.
To keep the definition compact, all symbols are based on a base class and a class for the icon, which achieves the effect. Note that the symbol is technically a character. If an icon appears on a button in the text or as an addition of a text, it should be separated by a space.

Buttons with icons

Messages with icons

Effect of a “close” button (nonfunctional)

Effect for drop-down menus (nonfunctional)
Images typically have natural expansion. On large screens this is not critical, but shown on small devices, they may leave the viewing area. With .img-fluid you can present better images.
max-width: 100%
height: Auto
display: Block
Thus, the image is scaled to the device width and remains stable. Should it be extremely reduced compared to the natural size, you may want to consider scaling with a server-side solution. By not doing so you waste a lot of bandwidth and have little effect on the user.
If .img-fluid is used, there are other options available. The class .center-block centers the image in the container.
In Internet Explorer 8 to 10 sVG (scalable vector graphics) images are scaled unfavorably with .img-fluid. to solve this, you should add the style rule width: 100%/9 to each image. Bootstrap does not do this automatically, because it has disadvantages for other formats.
1 <img src="..." class="img-fluid" alt="Responsive image">

Thumbnail effects on pictures
Embedded sources for video, audio, or external HTML pages are based on <iframe>-, <embed>-, <video>-, and <audio> elements.
.embed-responsive-16by9: Format 16:9
.embed-responsive-4by3: Format 4:3
Colors and backgrounds are global, so they provide variations of elements that have been provided.
text-muted: suppressed, bright, and gray.
text-primary: primary, main action, or primary statement, blue, important.
text-success: success, green, positive, or success.
text-info: information, azure, highlight, attention needed.
text-warning: warning, orange, action is consequential or message is critical.
text-danger: danger, red, errors or irreversible, serious warning.

Text colors
When allocated to an item, <p> is just another example that does not have the desired effect, and the use of another <span> element may be helpful. It is true that the weak semantic meaning is not accessible and screen readers do not reflect this information. Additional details that are hidden with .sr-only are the right solution.
Primary: primary, main action or primary statement, blue.
Success: success, green, positive or success.
Info: information, violet, highlight, attention needed.
Warning: warning, orange, action is consequential or message is critical.
Danger: danger, red, errors or irreversible, serious warning.

Background colors
When allocating to an item, <p> here is an example that does not have the desired effect, so the use of another <div> element can be helpful. The weak semantic meaning is not appropriate for accessibility and screen readers do not reflect this information. Again, additional details that are hidden with .sr-only are the right solution.
bg-light
bg-dark
bg-white
bg-transparent
The natural flow (sequence of elements) on a page can be changed by the classes .float-xx-left and .float-xx-right. The element is always pulled to the right or left edge, even if this means the natural order is changed. Internally, it is based on the style rule float.
This should not be done in navigation bars, where there are the specific classes .navbar-left or .navbar-right.
The element <center> is deprecated and should no longer be used with HTML 5.
You can also use .text-left and .text-right, respectively. To justify the text in a container where multiple lines are shown, consider using .text-justify.
One task a developer often has trouble with is controlling wrapping and overflow. This happens when the content is too big for the given container. Particularly in sites where the content is dynamic, it is often hard to predict how the elements look like in production. To control this, use the classes .text-wrap or .text-nowrap. With wrapping you allow the content to respect the width of the container and wrap at word boundaries. The element will grow vertically. With suppressed wrapping the content will exceed the element to the right, but the container remains the same. This behavior is called overflow. To cut the content, use .text-truncate. The part outside the container element will become invisible.
If a long word exceeds the container and wrapping is on, the result is a break in the middle of a word. That could render text unreadable. Here the class .text-break overrides the behavior and the long word “wins.” The container might still not have enough space, and therefore a horizontal scrollbar appears. That’s generally not attractive, but it keeps text readable.
lowercased text.
UPPERCASED TEXT.
Capitalized Text.
The option capitalized transforms the first letter into uppercase form. The other letters remain unchanged, regardless of their casing.
Use this carefully, as not all fonts support all styles. There is always a fallback, so text will remain readable. But if you use font weights to emphasize parts of the text, a missing style would make it hard or impossible to recognize.
A special form of transformation is .text-monospace. This is a nonproportional font, where each letter has the same width, making it perfect for code listings.
This code produces pseudoelements and sets the display mode to table. This creates an anonymous table cell in block format. The :before rule prevents the upper edge from collapsing with the previous element. This prevents a “stranger” distance that is disturbing. The :after rule generates the actual movement of the item onto the next line.
Even more powerful are the float-classes (.float-none, .float-left, .float-right) for alignment of elements outside their regular order. All these classes have variations to activate for certain breakpoints.
.d-none: hide on all breakpoints
.d-sm-none: hide only with “sm”
.d-md-none: hide only with “md”
.d-lg-none: hide only with “lg”
.d-xl-none: hide only with “xl”
.d-<>-block: display: block;
.d-print-block
.d-print-inline
.d-print-inline-block
.d-print-table
.d-print-none
The final document class looks (for example) like this: .visible-xs-block. The area that is designated will be displayed only if the screen is less than 768 px wide.
In this chapter we covered a few basic styles for common situations, such as text and background colors, alignment, and justification. Most classes can be used almost everywhere and can complement others.
Components are the building blocks taken from the Bootstrap library, and they provide certain functionalities that go beyond the mere use of CSS. Components are made from CSS with a combination of HTML, JavaScript, and font libraries.
This example assumes that you have copied the files into the production folder assets. Adjust the folders to match your build environment. In future versions of Bootstrap there are plans to replace the external dependencies with code delivered by Bootstrap directly.
Drop-downs—context or pop-up menus—are an integral part of many forms. The interaction is complex and partly based on JavaScript. It must not be activated separately; the data-attributes attach here, namely data-toggle="dropdown." Even menus benefit from symbols.

Menu folds downward

Menu tilted upward
The ability to “fold up” is limited to available space. If the button is at the top of the page and the menu would exceed the browser’s boundaries, it will fold down. This will not change the icon, which is still showing upwards.

Alignment related to the button element (left and right)
Decorative elements complement the menus. They should be used primarily to improve the readability of long menus and not simply as decoration.

Adding a subtitle

Divider line

Deactivated entry
The mouse pointer is set to a neutral pointer, while active entries show a hand.
Toolbars are technically groups of buttons. The buttons are horizontally next to each other. Embedded checkboxes, drop-downs, and radio buttons require JavaScript to work correctly. For drop-downs the additional library popper.js is a requirement.
With the .btn-group-group-classes a complete set of buttons can be made with resize.

Toolbar with buttons

Vertical toolbar with buttons
Each button can trigger pop-up menus. The button can appear in one or two parts. This requires you to add the popper.js library.

Toolbar with drop-down menu
The trigger for JavaScript is the attribute data-toggle="dropdown" (line 4). The black triangle image on the menu option is produced with the class .caret (line 6).

Toolbar with split button

Menu sizes
Note that the details have been changed as compared to those from Bootstrap 3. The smallest form is “sm.”
The navigation elements are all initiated by a common base class .nav. When navigating by tabulators, JavaScript is required. To support the accessibility attribute, role=“navigation” should be used in the logic overlying containers. This gives the navigation the necessary semantic meaning. The important thing is not to do so on the <ul>- element, but on the surrounding <nav> or <div> element.
Basically, distinction should be made in navigation between content navigation and navigation action. Content can be accessed via links, buttons, or tabs. However, navigation action takes place over buttons, menus, toolbars, menu strips, and so on. Forms are among the content. Only the submit button, for example, is an action.

Tabs
Note here the positioning of classes .nav-item and .nav-link.
The activating element is the attribute data-toggle="tab." Tabs that are to be activated with their own code do not carry this attribute.

Navigation buttons (pills)
JavaScript is required for full functionality. Bootstrap brings the code. It is activated via the attribute data-toggle="pill." Tabs that are to be activated with their own code do not carry this attribute.
Orientation
Deactivation
Folding menus

Disabled navigation buttons
The mouse pointer is neutral on the disabled element, while it is a hand on active entries.

Navigation buttons with menu
Moreover , the drop-down menu can be used with either data-toggle=“dropdown” foldable or data-toggle=“tab.” So it has either the behavior of a tab or a menu, but not both. A pull-down menu without a menu function is meaningless, so the only option is to use a part of the menu tabs without the tab function (a rare need).
The navigation bar (navbar) is a highly responsive element. You usually begin with a page that has complex content, with a menu bar at the top (see Listing 7-16). If the width is too small, the items will be outside the visible area (they vanish at the right side) and they are hence inaccessible by the user. This is where Bootstrap completely rebuilds the navigation bar. For this purpose, the elements are now arranged vertically and if the user decreases the view in the width further, the menu bar does not cover the entire page width.
Reduce the number of elements—must all elements really be accessible from the first page?
Depending on the width of the screen elements, they may be hidden dynamically—perhaps some functions are not useful for a small screen?
Adjust the menus targeted to all screens, possibly through their own media spaces.
The collapse of the broad menu to narrow requires JavaScript. You don’t need to add all components, as this feature is available through the collapse plug-in. The switch between narrow and wide defaults to 768 px.

Navigation bar (full width, Listing 7-16)

Navigation bar with a small screen (Listing 7-16)
The typical icon for a collapsed menu on small screens is called a “hamburger icon.” Instead of a font in the example, an UTF-8 character is used to present this. This might not be available in other fonts.
.navbar-dark
.navbar-light
These classes define the foreground color. For this to work a matching background color, for example .bg-primary, must be selected.
On a small screen, form elements can rarely be optimally placed. Take separate forms into consideration here, and try to simplify the arrangement further.
Continue to work for barrier-free access even if there is no space in the navigation bar. In such cases using .sr-only in combination with aria-label and aria-labelledby or the title attribute is best.

Application link
The alignment of the elements is accomplished with .navbar-left or .navbar-right, respectively. Because the elements usually consist of <li>, the uniform alignment is done on the surrounding <ul>.
The bar takes up space on the top of the page, though the definition is usually far deeper. This content is not superimposed intentionally; you may need a total of page height to get the upper distance: body { padding-top: 70px; }
The standard navigation bar (if no theme is used) is 50 px high.

Breadcrumb navigation
Ideally , the path shows not only where the user actually is, but allows navigation as well. Therefore, it is preferable that hyperlinks are used. The active element (class .active) is deactivated because the user is already at this location.
Even page-by-page scrolling belongs to the navigation elements. Usually it occurs in the context of data tables, but even multipage content pages can be browsed.
A typical setup for a few pages or a reasonably constant number of pages looks like this:
« 1 2 3 4 5 »

Page scrolling
If individual pages are inactive, for example, to display what is currently selected, either .disabled or .active is being used.

Navigation arrow buttons with partial deactivation
Add <li> tags for the page numbers and navigation, as shown in the previous examples. This usually depends on code that creates the numbering dynamically, according to the data the user is currently browsing.

Tag-pills in action

Labels in the navigation
If the badge has no content, it may render invisible. Consider adding a space entity ( ) or in case of numeric value, show 0 instead of nothing.
The classes available in older Bootstrap versions, such as .label or .tag, have been deleted to avoid confusion with the <label> element.

Introduction on a page
alert-primary: blue standard
alert-secondary: gray standard
alert-success: success message, green
alert-info: information, azure
alert-warning: warning, orange
alert-danger: error, red
alert-light: neutral light gray on white background
alert-dark: neutral gray background with black text

Output messages

Messages that are closable

Messages with further link

Passive progress bar
progress-bar bg-success: success, green
progress-bar bg-info: information, azure
progress-bar bg-warning: warning, orange
progress-bar bg-danger: danger or critical, red

Semantic progress bar

Semantic progress bar with stripes

Interactive progress bar
The script determines the number of options (line 2). Each time you click, the number of active members is determined by a checkbox (line 4). The display and the width are controlled by the calculated percentage. The text in line 9 hides the number 0, so that the display without bars is empty.
The classes .align-self-start and .align-self-end align the element on the page (top or bottom).

Lists for grouping

Lists with tags

Lists of links

Lists with buttons
list-group-item-success: success, green
list-group-item-info: information, azure
list-group-item-warning: warning, orange
list-group-item-danger: danger, red

Semantic lists with and without links

Lists with headings
Semantic and nonsemantic meaning is achieved with background classes (.bg-<type>).

Card with class .card-danger
If the font color has an insufficient contrast, you can get a better representation using the class .text-light. This makes sense at least in danger class, where the font color changes for the dark red background from black to white.
The standard menu is preceded by .card. A general internal spacing (padding) is achieved with .card-body. The text is created in .card-text.
Cards can create complex reports and can include a header area. This part is preceded by .card-header. In the header, the size can be varied with <h1>-<h6>.

Card with heading

Card with title and heading element
It is also possible to place subheadings on .card-subtitle.

Semantic card with footer
The card presentation of data provides tables for output, too. Note, however, that there are limited possibilities for responsive layouts with tables. Because cards already have a frame, tables should be drawn without them.

Card with table
Within .card-text there is a seamless transition between content and table.

Card with list

Card with background image
The image should be tailored to the width of the card, as shown in Listing 7-43 on line 2, to 300 px. Please note that such fixed values may not be responsive.
There is the option to combine the width and the distance to the column classes for placement in the grid.
.card-img-top: aligning the image upward
.card-img-bottom: aligning the image downward; these classes are directly applied to the <img /> tag.

Cards in the grid

Align cards

Card group
The horizontal alignment may be connected to the column layout, so that you also can control the width.

Card columns
In this example the semantic classes .card-outline-<> is used to assign the color to the border only. This replaces the regular .card-<> classes that give cards a semantic meaning.
This chapter provided an overview of layout components used to create the essential visual parts of an application. This includes important design elements such as navigation, message boxes, and buttons. The card component is another piece that is very universal and can be used to further structure your pages.
Active components in Bootstrap are written in and supported by JavaScript. This includes some programming interfaces to work with. Technically these are jQuery plug-ins. If the entire Bootstrap library is not used, it is possible to load only those parts that are really needed.
The files bootstrap.js and bootstrap.min.js (the minimized version) already contain all the components. To use this you also need to load jQuery. To use the components there are two options: either you use the HTML5 attributes beginning with data- or the JavaScript API. For the purposes of modern HTML5 programming, using attributes is preferred because it needs less script code, and thus there is less risk of making mistakes when programming.
In more complex scenarios, there is often the temptation to use multiple plug-ins with a component. This will not work. Imagine a button that activates a modal dialog and simultaneously displays a tooltip. Although this may be useful in design, it will not work. This can be achieved simply with another enclosing member. The outer member—without frames and distances—controls the tooltip and the inner one the modal dialog.
There are several frameworks for web site programming, such as Angular, React, or Vue. Some competing UI libraries exist, such as jQuery UI. Although jQuery is the basis of Bootstrap components, these frameworks compete with Bootstrap and should not be used simultaneously under any circumstances. Often you can find a compatibility library that handles the conflicts (for example,with Angular you may use ngBootstrap instead of Bootstrap, and have the same components but in Angular style).
The leading $ sign is a function call (JavaScript allows the $ literal as a name). That call queries the page for the given selector, which follows CSS rules. It returns another jQuery instance, so you can immediately execute functions on the selected elements. Like the functions delivered with jQuery, Bootstrap adds more such calls for the components described in this chapter.
The leading $.fn. is the access to registered plug-ins in jQuery. This part is not specific to Bootstrap, but is a requirement of jQuery.
This is an example of a “popover.”
In line 1, an instance of the plug-in is retrieved. This is then assigned a new name in line 2, which does not interfere with other elements.
Bootstrap components generate some private events. Most of these are available in two versions—the occurrence of the event and the end of processing. Accordingly, the verbs are available: basic and past tense (“show” and “shown”). All events are in their own namespaces “.bs.”.
Here the code in line 2 prevents the standard behavior. The modal dialog, which actually appears in “show,” is suppressed. Of course, only events that currently occur can be suppressed, such as “show.” If the event has been completed, as in “shown,” there is no longer such an option.
Transitions are largely covered by CSS3. To support older browsers, there are covered by the auxiliary library transitions.js, mapping the effects in JavaScript. This library is part of bootstrap.js and does not need to be installed separately. This is only necessary when parts of the library are used.
Animations—whether as direct effect or transition—are only amusing the first time. Omit them, and users benefit.
Dialogues are gently faded in and out.
Switching between tabs is changed gently.
Messages can be smoothly displayed.
The Carousel has replaced its content with animation.
The effect is triggered by the class .fade.
Modal dialogs are from modals.js. This library is part of bootstrap.js and does not need to be installed separately.
Modal dialogs seize exclusive focus and demand an unconditional response from the user. You should never use modal dialogs without the possibility of interaction. A button or an icon for closing is always required.
A modal dialog is exclusive, so only one dialog at a time can be open.
Normally you should place modal dialogs on top of the page. This prevents conflicts with other settings. When and where they are called, however, is completely independent.
Header area
Content
Footer area

Modal dialog
As with previous examples, a barrier-free access is recommended. First take the attributes role=“dialog” and aria-labelledby=“…”; the latter should point to an element that contains the title. As the dialogue itself, the contents are decorated with role=“document.” If a description is required, which may not appear useful in normal operation because the dialogue is in a context or contains images and symbols, use the more descriptive aria-describedby on the element with the class .modal.
.bs-example-modal-lg: greater than normal
.bs-example-modal-sm: smaller than normal
Animations are created with .fade. This can be annoying, and should not be used on mobile devices.
The effect of fading requires significant processing power and reduces the battery life in mobile devices

Using the grid withing a dialog

Controlled dialog
Modal dialogs will give the page a slightly opaque look, to catch the attention of the user. That is done internally by adding the class .modal- open to the body element. You can give to this class more styles to customize the effect. Agent .modal-backdrop used another class that ensures that the dialog will be closed when the user clicks outside (despair click).
data-toggle="modal": trigger, for example, on a button
data-target="#foo": target for dialogue #foo
href="#foo": alternative specifying the destination for dialog #foo
id="foo": decoration of the dialogue itself (destination ID)
Name | Type | Description |
|---|---|---|
backdrop | Boolean or “static” | True will close when clicking outside; “static” suppresses closing |
keyboard | Boolean | Closes the dialog when ESC is pressed |
show | Boolean | Instant display during initialization |
focus | Boolean | Moves focus (caret position) to the dialog |
Name | Description |
|---|---|
show | Dialog appears |
toggle | Toggle display state asynchronously |
hide | Close |
handleUpdate | Repositions by moving or showing the scrollbar |
dispose | Destroys the element |
Name | Description |
|---|---|
show.bs.modal | Dialog appears |
hide.bs.modal | Dialog closing |
shown.bs.modal | Appears (on transitions, and animations will be serviced) |
hidden.bs.modal | Has been closed (on transitions, and animations will be serviced) |
loaded.bs.modal | Is loaded |
hidePrevented.bs.modal | If the dialog is already open, the backdrop is “static” and the user clicks outside (or hits ESC), this event fires; usage is to prevent closing the dialog |
The drop-down menu is available in a simple form without JavaScript support (already covered in Chapter 7). The possible interactions enhance the function of navigation bar (navbar), tabs, and pills. For more advanced scenarios, additional coding effort is required.
Show invisible elements dynamically and again hide can be carried out by turning on and off the class .open. On mobile devices .dropdown-backdrop will work for the whole screen and “tap” for the event. That is, it does not automatically close the menu on such devices, but must be closed with extra finger pressure before another menu item can be selected.
The attribute data-toggle=“dropdown” is always required.
Name | Description |
|---|---|
offset | Move the drop-down using a pixel value or a callback function |
flip | Flip if the drop-down overlaps the element (default behavior) |
boundary | Control the overflow with “viewport,” “window,” “scrollParent,” or an HTMLElement reference |
reference | Use “toggle” or “parent” or an HTMLElement reference to access the drop-down element |
display | Use “dynamic” or “static” for positioning |
popperConfig | Configure the underlying popper.js library |
Name | Description |
|---|---|
toggle | Display state changes to opposite |
show | Show the drop-down part |
hide | Hide the drop-down part |
update | Update the position; necessary if the surrounding elements change their position and the drop-down button moves up or down, in which case a formerly positioned menu would stay at the last position |
dispose | Destroy the element’s drop-down |
Name | Description |
|---|---|
show.bs.dropdown | Show |
hide.bs.dropdown | Close |
shown.bs.dropdown | Display was (on transitions and animations will be serviced) |
hidden.bs.dropdown | Has been closed (on transitions and animations will be serviced) |
loaded.bs.dropdown | Is loaded |
This component recognizes the position of the scroll bar. The jump destinations can be dependent on the update position of the scroll bar in a navigation bar. This is especially interesting for very long pages, where the jump destinations in a list of hyperlinks at the side are left or right and above that are always visible. When the user clicks on a link, the page jumps to the target position. This is normal browser behavior. However, if the scroll bar is used, a certain position sometimes appears. With Scrollbar-supervisor the menu is then suitably adjusted to the position so that the current visible section is highlighted. For the menu to display this effect, it must remain visible while scrolling. The purpose should be tacking navigation. This can be achieved with position: sticky. The affix component from Bootstrap 3 no longer exists.
First, a navigation component is needed. The resolution of the jump destinations must be done on id. An object that was created with <a href="#home">home</a> must lead to a matching <div id="home"></div>. Invisible elements are ignored. The criterion for visibility applies, when jQuery uses the pseudoselectors: :visible indicators. This monitors the scroll area of an element. It needs position:relative to be positioned. This is usually <body> and there is no further action required. It is another element that also must accommodate overflow: scroll and a height must also be specified.
Options may be set as a data--attributes in HTML or with code.
Name | Type | Description |
|---|---|---|
offset | Number | Distance from the top, is responsive to the appearance of the target elements; default value is 10 pixels |
method | String | Finds the spied section; can be “auto,” “offset,” or “position.” |
target | Element | The element the scrollspy is applied; can be any form jQuery accepts (string, jQuery object, DOM element) |
Name | Description |
|---|---|
refresh | Synchronizes dynamic elements |
Name | Description |
|---|---|
activate.bs.scrollspy | Activated |
Reversible tabulators can be modified by other elements. This is only supported on one level, and not for nested elements. This is the active part of the navigation element made with the .nav-tabs class described in Chapter 7. The purpose is to control the content of a tab in addition to the tab’s navigational items.
The code in line 1 uses a name; line 2 selects the first tab, line 3 the last. Line 4 is the third (2, that is, the value is 0-based) selected.
Name | Description |
|---|---|
show | Shows the component |
dispose | Destroys the component |
Name | Description |
|---|---|
hide.bs.tab | Tab is hidden |
show.bs.tab | Tab is shown |
hidden.bs.tab | Tab was hidden (by animation) |
shown.bs.tab | Tab has been displayed (after animation) |
Note that there is no “hide,” because one tab is always active. If one is enabled, all others are hidden.
Tooltips serve to provide useful information for the user (see Listing 8-8). They respond to a floating (hovering) mouse. Because showing many tooltips is critical to the performance of the browser they must be self-activated—the attributes alone are not enough.

The tooltip in action
Sometimes the tips are somewhat more complex and have multiple lines. Normally, the text will automatically wrap and center. With white-space: nowrap; this upheaval is prevented. If such a tip in groups of buttons (with .btn-group or .input-group) is used, further measures are needed. In JavaScript, the container must be specified where the generated code is implanted in the DOM. In most, container: ‘body’ is sufficient.
Tooltips for invisible elements are not a good idea. The tip will not be correctly placed, because the position of the reference element cannot be determined. View the reference element only and release the tooltip after its parent element becomes visible.
Otherwise, tooltips should only be used if the elements are being triggered by keystrokes. This can be achieved if you are limited to input elements. If this is not possible, use the attribute tabindex for an item to make it explicitly accessible.
Name | Type | Description |
|---|---|---|
animation | Boolean | Animation on the appearance |
container | string or false | Positioning in another element |
delay | number, object | Delay in milliseconds (default: 0), can also be an object { “show”: 10, “hide”: 10 }, then apply for the ads and hide different values |
html | Boolean | HTML is allowed in the text |
placement | string, function | Place the tip using “top,” “bottom,” “left,” “right,” and “auto” place so that the tooltip is always shown; for a function, they are determined by position itself |
selector | String | To select the destination as a selector |
template | String | Template in HTML |
title | String | Content (text) of tooltips |
trigger | String | Trigger: click, hover, focus, manual. Standard: “hover focus” |
viewport | String, object, function | Standard: { selector: ‘body’, padding: 0 } or a selector or a selection function |
Name | Description |
|---|---|
show | Show |
hide | Hide |
toggle | Change from show to hide or vice versa |
dispose | Destroy the component |
Name | Description |
|---|---|
hide.bs.tooltip | Tooltip is about to hide |
show.bs.tooltip | Tooltip is about to show |
hidden.bs.tooltip | Tooltip is hidden (by animation) |
shown.bs.tooltip | Tooltip is shown (after animation) |
inserted.bs.tooltip |
The text appears in .tooltip-inner.
The somewhat cumbersome term content overlay (popover) represents a brief appearance, but not a modal dialog, usually without interaction. The most important applications are for giving detailed help. This is always appropriate when tooltips are no longer sufficient. Because many overlays are critical to the performance of the browser, they must be explicitly enabled; the attributes alone are not enough.
Content overlays can be static or dynamically activated. Static—constantly visible elements—usually serve design purposes.
The popover feature requires an additional library, “popper.js.” There are also different styles available. This is the same as for tooltips.

Popover placement
If the triggering element is a hyperlink, it can occur on narrow screens. Only then the content of the hyperlink is multiline, and the content superimposition is both horizontal and vertical. This can be inconvenient, because it interferes with the text of the triggering element. With the style white-space: nowrap; on the hyperlink that behavior can be avoided.
For this to consistently work, the trigger should be a hyperlink, not a button.
Name | Type | Description |
|---|---|---|
animation | Boolean | Animation on appearance |
container | String or false | Positioning at another element |
delay | Number, object | Delay in milliseconds (Default: 0) can also be an object: { “show”: 10, “hide”: 10 } then apply for ads and hides different values |
html | Boolean | HTML is allowed in the text |
content | String | Default content if the element delivers nothing |
placement | String, function | “top,” “bottom,” “left,” “right,” “auto.” With the value “auto” the tooltip is always displayed. When a function is used, the position is determined by this function |
selector | String | To select the destination as a selector |
template | String | Template in HTML |
title | String | Content (text) of tooltips |
trigger | String | Trigger: click, hover, focus, manual. Standard: “hover focus” |
viewport | String, object, function | Standard: { selector: ‘body’, padding: 0 } or a selector or a selection function |
Name | Description |
|---|---|
show | Show |
hide | Hide |
toggle | Switch view state |
enable | Enable (default) |
disable | Make temporarily not function |
dispose | Destroy the element |
Name | Description |
|---|---|
hide.bs.popover | Popover is hiding |
show.bs.popover | Popover appears |
hidden.bs.popover | Popover was hidden (by animation) |
shown.bs.popover | Popover was shown (by animation) |
inserted.bs.popover | Return to “show” if the item is placed in the DOM |
The text appears in an element with the class .popover-content.
The alerts component produces the same messages to those made with just the class .alert.
Action buttons respond to states and display them.
Name | Description |
|---|---|
toggle | Toggle the state |
dispose | Destroy the component |
Similar content overlay creates the content display (or content suppression, depending on how you look at it). In any case, this element is used to display only temporarily unnecessary content and then releases valuable space again.
The trigger to switch the group is data-toggle=“collapse.” This either can be a link (with href=“#targetId”) or a button (with data-target=“selector”).

Content is displayed dynamically
aria-expanded: indicates which group is open
aria-controls: indicates which group is controlled by link
aria-labelledby: indicates which head area refers to the group
The accordion is a frequently used element that offers many design frameworks. Technically, this is a group of navigation elements and dynamic panels that are displayed exclusively in each case.
The individual components have all been introduced. In Bootstrap the accordion is not a stand-alone component, but a combination of basic building blocks.
The code uses the data-attributes and design of the.card class with related classes. The trigger for the switching of the group is data-toggle=“collapse.” This can either be a link (with href=“#targetId”) or a button (with data-target=“Selector”). When you open a group, the group that is already open closes automatically, which is data-parent=“id” and uses the ID that refers to the surrounding container element.

Contents display
Use either “data-”-attributes or JavaScript. If both are used simultaneously, the script gets confused and the accordion behaves illogically.
Use either “data-”-attributes or JavaScript. If both are used simultaneously, the script gets confused and the accordion behaves illogically.
Options may be set as a “data-”-attributes in HTML or with code.
Name | Type | Description |
|---|---|---|
parent | String | Selector for the parent element automatic switch |
toggle | Boolean | Toggles the collapsible element on invocation |
Name | Description |
|---|---|
show | Show the element |
hide | Hide the element |
toggle | Switch view state |
dispose | Destroy the component |
Name | Description |
|---|---|
hide.bs.collapse | Content is hidden |
show.bs.collapse | Content is displayed |
hidden.bs.collapse | Contents were hidden (by animation) |
shown.bs.collapse | Content has been displayed (after animation) |
The gyro images (often called carousel) are used to display a picture or content path, which has always just one element that is currently visible.

An image of one of the carousel states
This component is not suitable for accessible environments.
Name | Type | Description |
|---|---|---|
interval | Number | Time until the next element, default is 5,000 ms |
pause | String | Stops the indexing, as long as the mouse is over the element |
wrap | Boolean | Continuous indexing or stepwise |
keyboard | Boolean | Responds to the keyboard |
ride | string | Autoplay |
touch | Boolean | Activate touch support |
Name | Description |
|---|---|
cycle | Change to the next item |
pause | Stop |
prev | Previous entry |
next | Next entry |
dispose | Destroy the component |
Name | Description |
|---|---|
slide.bs.carousel | Start a movement |
slid.bs.carousel | End a movement |
In this chapter you learned the JavaScript-API and how to get additional functionality through programming the components with just a few lines of code. Some components do not function without JavaScript properly. This is why it’s important to have the API handy even if there is no need to change the default behavior.