Bootstrap Ant 1
Bootstrap Ant 1
Bootstrap
A SitePoint Anthology
July 2016
Notice of Rights
All rights reserved. No part of this book may be reproduced, stored in a retrieval system or transmitted.
in any form or by any means, without the prior written permission of the publisher, except in the case of
brief quotations embodied in critical articles or reviews.
Notice of Liability
The authors and publisher have made every effort to ensure the accuracy of the information herein
However, the information contained in this book is sold without warranty, either express or implied
Neither the authors and SitePoint Pty. Ltd., nor its dealers or distributors will be held liable for any
damages to be caused either directly or indirectly by the instructions contained in this book, or by the
software or hardware products described herein.
Trademark Notice
Rather than indicating every occurrence of a trademarked name as such, this book uses the names only
in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the
trademark.
Web: www.sitepoint.com
Email: [email protected]
Contents
The Rise of the Puss in Bootstrap
12
Responsive Images
13
Creating Columns
13
16
17
17
18
19
Helper Classes
20
20
22
23
26
26
27
28
29
DropDown31
ScrollSpy32
Tabs32
ToolTip33
Popovers33
Alerts34
Conclusion35
The Demo Page Set Up
36
43
Conclusion54
55
56
57
Why Masonry?
56
60
61
63
Conclusion64
65
What Is Bootstrap?
66
72
68
73
74
Introducing Animate.css
75
76
75
79
79
Conclusion83
84
Installation85
Conclusion89
90
91
92
Reusability94
Portability94
Fill Your Toolbelt
94
96
94
97
104
Conclusion106
the mockups from the designers, painstakingly counting the pixels and crafting the CSS with lots of
care and patience. Countless hours would be spent in an (often futile) attempt to obtain a pixel-perfect
reproduction of the design concepts across the range of supported browsers.
Things started to change in August 2011, when a new hero rose to challenge the web. Born from the
passion and dedication of Mark Otto and Jacob Thornton, the newborn Bootstrap took the front-end
development kingdom by storm. The second version came fast, after only half a year and it was built
along the principles of responsive web design. It boasted a robust twelve column grid, lots of pre-styled
components and it allowed almost everyone to put together a basic webpage, just as easy as stacking
together LEGO pieces. And just on its second birthday came the announcement of the evolution to
version 3, featuring a mobile-first approach and ditching the previous Web 2.0 gradients in favor of the
flat design. Two more years later, in August 2015, the first alpha version of the fourth iteration became
available to the wide community. The rapid development cycle seems to have been paused though, as
at the time these words were written, no further public advancement of the fourth version has happened.
I dare say that Bootstrap had almost the same effect on the World Wide Web as Ford's assembly line had
for automotive industry. Every Joe and Jane with a minimum of knowledge in the field of front-end
technologies could now put together a basic website that worked well across a large variety of devices
and browsers. Sure, on one hand, most of them are similar to thousand others, to the point where many
people started complaining that "Bootstrap is killing web design". On the other hand there are true
masterpieces of design and craftmanship, that you can admire on dedicated websites such as the official
Bootstrap Expo or BuiltWithBootstrap.
So here we are, almost 5 years from the birth of Bootstrap. In this time it grew from an internal frame-
work at Twitter to the most used UI/front-end framework on the web, with more than 7 million web-
sites using it (according to BuiltWith.com). Despite the apparent break in the development cycle, version
3.X.X of Bootstrap remains a solid option for building up your websites and web apps.
This is where this book comes in. Beginners will find a wealth of knowledge to help them start on this
new and fascinating road. Andvanced developers will discover small tricks and tips, designed to make
their lives easier. One thing is sure though: Bootstrap is here to stay!
Bootstrap include in its CSS to help with this? Let's examine a few
things and gain some insight that might help us in our own custom
projects.
@fazlerocks
Bootstrap has clearly defined breakpoints for different kinds of devices, specified by using CSS media
queries. The following are the breakpoint categories used for the different types of devices:
1. Extra Small Devices (e.g. cell phones) are the default, creating the mobile first concept in
Bootstrap. This covers devices smaller than 768px wide.
2. Small Devices (e.g. tablets) are targeted with @media (min-width: 768px) and
(max-width: 991px) { ... }.
3. Medium Sized Devices (e.g. Desktops) have a screen size smaller than 1200px and greater than
991px, using @media (min-width: 992px) and (max-width: 1199px) { ... }.
4. Larger Devices (e.g. wide-screen monitors) are greater than 1200px, targeted using @media
(min-width: 1200px) { ... }.
Note: Mobile devices that we use today come with 2 different screen orientations:
Portrait and Landscape. So the above is mostly true for landscape view only. For
example, if you are using a Samsung Galaxy Note III phone, the landscape view
falls in the Small Devices category whereas the portrait view would fall under
Extra Small Devices.
This kind of categorization is common in responsive frameworks and it's something you can certainly
benefit from understanding better.
As shown above, Bootstrap's grid system starts with a container element. Containers define how much
space a grid system should use. They can be of two types: .container has different widths for
different types of devices whereas .container-fluid expands to fit the width of the device.
With the help of media queries, Bootstrap gives different widths to the .container depending on the
size of the device:
Bootstrap container
As seen in the above image, the .container prevents the content inside the element from touching the
browser edge using 15px of padding on each side. It also ensures the container is centered using auto
Rows are another important element in Bootstrap's Grid System. Before creating columns, you can
define a row using the class .row. Here's a snippet from Bootstrap's CSS for the .row class:
.row {
margin-right: -15px;
margin-left: -15px;
}
As shown above, our row has negative left and right margins of -15px to allow the row to touch the edge
of its container element. This acts as a wrapper to hold columns, which can add up to 12 in number.
Bootstrap row
You may have noticed that the margins on the row seem to be counteracting the 15px of padding applied
to the container. If we analyze the columns, we can see why this is needed.
Here's a snippet from Bootstrap's CSS for the .col-xs-6 class.
.col-xs-6 {
padding-right: 15px;
padding-left: 15px;
}
As shown, left and right padding of 15px is applied to the columns, resulting in something like the
image below:
Because of the negative margins on the row, the columns are touching the edges of the row and the
edges of the container. But the padding causes the contents that go inside these columns to remain 15px
Containers are used for multiple purposes, not just for the grid system, so the 15px padding helps to
avoid the content touching the edges of the browser (when using .container-fluid). Rows have the
negative margins so that they are not pushed by the padding of the container.
If you are considering designing your own framework, you might want to consider using this padding/
margin technique.
As stated above, there are 4 different categories of device-based breakpoints. Each category has its own
set classes for columns of different sizes.
The asterisk character * gets replaced by a number. For example, .col-xs-6 creates a column 6 times
the size of a .col-xs-1 column; .col-sm-4 creates a column four times the size of .col-sm-1, and
so on.
By default, all the columns have no width set, which defaults to width: auto. However, within the
Here's a snippet from Bootstrap's CSS for the column classes with asterisks replacing the sizes for brevity
{ width: 75%; }
.col-*-8
{ width: 66.66666667%; }
.col-*-7
{ width: 58.33333333%; }
.col-*-6
{ width: 50%; }
.col-*-5
{ width: 41.66666667%; }
.col-*-4
{ width: 33.33333333%; }
.col-*-3
{ width: 25%; }
.col-*-2
{ width: 16.66666667%; }
.col-*-1
{ width: 8.33333333%; }
Let's analyze the above code. A class .col-lg-6 will have a width of 50% in large devices but when
12 - Bootstrap: A SitePoint Anthology
viewed in medium, small, and extra-small devices, the default width: auto is used. This ensures that
the columns are converted to a stacked layout (rather than side by side) in smaller devices.
Responsive Tables
Tables, used for displaying tabular data, are also responsive in Bootstrap. To use Bootstrap's table styles,
we use the class .table, which has the following CSS:
.table {
width: 100%;
max-width: 100%;
margin-bottom: 20px;
}
Bootstrap forces tables to fit the width of the parent element by applying a width of 100%. But this has
an issue. A multi-column table will get squeezed on smaller devices and may not be readable.
Bootstrap has another class to remedy this: .table-responsive. Here's the CSS:
.table-responsive {
width: 100%;
overflow-x: auto;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
-ms-overflow-style: -ms-autohiding-scrollbar;
border: 1px solid #ddd;
}
These styles cause the table to become scrollable on the horizontal axis on smaller devices.
Responsive Images
Working with larger images may be a problem for smaller devices. Bootstrap uses a class of
max-width: 100%;
height: auto;
}
This combination of max-width: 100% and height: auto will ensure the images scale down
proportionally in smaller devices, while staying within the parent element's constraints on larger devices.
Understanding Bootstraps
Grid System
Bootstrap is undoubtedly one of the most popular front-end
frameworks. With more than 73k stars and 27k forks, Bootstrap is
we will discuss a related topic: The Grid System, one of the most
important concepts in Bootstrap.
Think of graph paper, where every page has a set of vertical and horizontal lines. When these lines
intersect, we get squares or rectangular spaces.
Graph paper
Now the question is, how many rows and columns you can create using Bootstraps Grid System?
Bootstrap allows you to create up to 12 columns and unlimited rows hence the name 12-Grid
System. So, lets see how we can utilize this grid system to create various types of layouts.
3. Columns
Creating a Container
Bootstraps grid system needs a container to hold rows and columns. A container is a simple <div>
element with a class of .container. The container is used to provide a proper width for the layout,
acting as a wrapper for the content. Here is the code for this task:
<div class="container">
Some content
</div>
Here the container element wraps the content and sets left and right margins. It also has different fixed
Device Width
1200px or higher
992px to 1199px
768px to 991px
Less than 768px
Container Width
1170px
970px
750px
auto
You can choose a fluid container if you are not fond of a fixed layout. To do this, you use the class
.container-fluid. A fluid container has no fixed width; its width will always be the width of the
device.
Just note that both fixed and fluid containers have padding of 15px on the left and right sides.
Creating a Row
A row acts like a wrapper around the columns. The row nullifies the padding set by the container
element by using a negative margin value of -15px on both the left and right sides.
A row spans from the left edge to the right edge of the container element. It is created by adding the class
In this demo, you can see the text touching the left edge of the container element. This is because the
containers padding has been removed by the row due to the negative margins on the row.
Finally, theres no limit on the number of rows you can create.
Creating Columns
Bootstrap uses different column class prefixes for different sized devices. These prefixes are shown in the
table below:
Class Prefix
.col-xs.col-sm.col-md.col-lg-
Device Size
< 768px
768px to 991px
992px to 1199px
1200px
In the above demo, I used the class .col-xs-12 to create a single column that spans across 12 virtual
Bootstrap columns. Hence, this columns width will be the width of the row.
In the above demo, you will also see the 15px padding reappear to push the element away from the
You must be wondering why I used the class prefix that belonged to extra smaller devices, which is
.col-xs-. In Bootstrap, if a column is defined for a particular type of device then it is guaranteed to
behave similarly in larger devices as well. Therefore, a column defined for extra smaller devices will
Lets now create a 2-column layout for smaller devices and check out its behaviour in larger devices and
extra-small devices. We will use the class prefix .col-sm- here. To create 2 columns of equal widths,
we should assign 6 virtual Bootstrap columns to each one of them. This way, we maintain the limit of 12
We understand that to use Bootstraps grid system, we need 3 things: A container, rows, and columns. So
to nest a grid system within a column we will need the same three things. But the only difference is that
the container is already defined. In this case, the columns will behave as the containers for the nested
grid system.
Heres the logic: The containers provide 15px of padding, which is nullified by the row. Then we define
columns that again have 15px of padding on the left and right side. So, to nest a grid system within a
column, we simply need rows and columns. No .container or .container-fluid elements are
necessary for a nested grid system.
In such a case, a virtual row will be created and unfitted columns will shift to the next row. For example,
if you have defined 2 columns with the classes .col-md-8 and .col-md-5, the second column will
shift to a new row because it requires 5 virtual Bootstrap columns whereas only 4 are left.
Helper Classes
Bootstrap provides various helper classes that can be useful in certain situations in dealing with grids.
}} .clearfix: Normally used to clear floats, adding this class to any column will make it shift to a
new row automatically, to help you correct problems that occur with uneven column heights.
}} Offsetting columns: You dont have to occupy all 12 of the virtual columns. You can use offset
classes like .col-xs-offset-* or .col-md-offset-* to leave a particular number of virtual
Bootstrap columns to the left of any column (kind of like invisible place holders).
}} Reordering: Use classes like .col-md-push-* and .col-md-pull-* to shift a column to the
right or left, respectively.
Understanding
Bootstrap Modals
@fazlerocks
novice designers. It ships with some of the best ready-to-use JavaScript and jQuery components and
plugins. Here we will be talking about one of the most useful jQuery Bootstrap plugins - The Modal.
The Bootstrap Modal is a lightweight multi-purpose JavaScript popup that is customizable and responsive. It can be used to display alert popups, videos, and images in a website. Websites built with
Bootstrap can use the modal to showcase (for example) terms and conditions (as part of a signup
process), videos (similar to a standard light box), or even social media widgets.
Now lets examine the different parts of Bootstraps modal, so we can understand it better.
The Bootstrap Modal is divided into three primary sections: the header, body, and footer. Each has its
own significance and hence should be used properly. Well discuss these shortly. The most exciting
thing about Bootstraps modal? You dont have to write a single line of JavaScript to use it! All the code
and styles are predefined by Bootstrap. All thats required is that you use the proper markup and the
attributes to trigger it.
To trigger the modal, youll need to include a link or a button. The markup for the trigger element might
look like this:
Notice the link element has two custom data attributes: data-toggle and data-target. The toggle
tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a
Now lets see the code required to define the modal itself. Here is the markup:
Bootstrap: A SitePoint Anthology - 23
The parent div of the modal should have the same id as used in the trigger element above. In our case it
would be id="basicModal".
need place the three sections I mentioned earlier: the header, body, and footer.
The modal header, as the name implies, is used to give the modal a title and some other elements like the
x close button. This should have a data-dismiss attribute that tells Bootstrap which element to hide.
Then we have the modal body, a sibling div of the modal header. Consider the body an open canvas to
play with. You can add any kind of data inside the body, including a YouTube video embed, an image, or
just about anything else.
Lastly, we have the modal footer. This area is by default right aligned. In this area you could place action
buttons like Save, Close, Accept, etc., that are associated with the action the modal is displaying.
Now we are done with our first modal! It should look like in the image above.
The modal comes in two new flavors in Bootstrap 3: Large and Small. Add a modifier class modal-lg to
the modal-dialog div for a larger modal or modal-sm for a smaller modal.
The options here would be a JavaScript object that can be passed to customize the behaviour. For
example:
var options = {
"backdrop" : "static"
}
backdrop: This can be either true or static. This defines whether or not you want the user
}} keyboard: if set to true then the modal will close via the ESC key.
}} show: Used for opening and closing the modal. It can be either true or false.
}}
remote: This is one of the coolest options. It can be used to load remote content using jQuerys
load() method. You need to specify an external page in this option. It is set to false
by default.
You can further customize the normal behaviour of the Bootstrap modal by using various events that are
triggered while opening and closing the modal. These events have to be bound using jQuerys .on()
method.
}}
loaded.bs.modal: fired when remote content is successfully loaded in the modals content area
You can provide a value to the href attribute inside the modals trigger element. In our case, the trigger is
a link. For example, instead of the # value we included earlier, we can include a URL to a specific page:
<a class="btn btn-lg btn-default"
data-toggle="modal"
data-target="#largeModal"
href="remote-page.html">Click to open Modal</a>
You can also provide a custom data attribute of data-remote to the trigger element instead of using the
26 - Bootstrap: A SitePoint Anthology
Conclusion
The modal is one of the best plugins offered by Bootstrap 3. For a novice designer, it is one of the best
ways to load content inside a popup screen without writing any JavaScript.
Bootstrap JavaScript
Components
Bootstrap happens to be the easiest and the best CSS framework on
to build basic templates without any efforts. But this doesn't stop designers from using Bootstrap.
Bootstrap has one of the best sets of powerful JavaScript components. These components are easy to
use and are usable in your web project, today. Here I will discuss some of the best Bootstrap JavaScript
The first thing that we should understand is that Bootstraps JavaScript components are written in
jQuery. So we need jQuery to work with them. After you have downloaded Bootstrap 3, copy the
contents of the dist folder and paste it inside a new work-space. You must be thinking why do we need
the CSS and fonts folder when we are going to learn JavaScript? There are many Bootstrap JavaScript
components that depends on CSS to work properly. So unless you include the Bootstrap CSS it wont
28 - Bootstrap: A SitePoint Anthology
function properly. Bootstrap 3 also allows us to use each module individually instead of downloading
all the JavaScript components. We will see at the end of this tutorial how to use a single module instead
of including all the components. Some of the main Bootstrap JavaScript components explained in this
tutorial are:
1. Modal
2. Dropdown
3. ScrollSpy
4. Tab
5. Tooltip
6. Popover
7. Alert
We will cover each of them in this tutorial. We will also experiment a bit with each component so that we
get a customized Bootstrap 3 JavaScript component.
Modal
A modal is a dialog prompt just like a traditional alert. It comes with advanced features like modal title,
modal body, modal footer, close button and a close symbol at the top right corner. It can be used as a
confirmation window in many applications such as before making a payment, or deleting an account,
etc. A Modal has three sections: header, body and footer. You can decide what to place in each of them.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
Bootstrap: A SitePoint Anthology - 29
<div class="modal-body">
<h1>Hello World!</h1>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
modal
DropDown
30 - Bootstrap: A SitePoint Anthology
Creating a drop down menu in Bootstrap 3 gets extremely easy. You just have to understand right
markup required. You can use this DropDown in a navigation bar or inside any div you wish.
<div class="dropdown">
<a data-toggle="dropdown" href="#">Show Links <b class="caret"></b></a>
<ul class="dropdown-menu" role="menu">
<li><a href="#">First Link</a></li>
<li><a href="#">Second Link</a></li>
<li role="presentation" class="divider"></li>
<li><a href="#">Third Link</a></li>
</ul>
</div>
dropdown
First, you have to give the class "dropdown" to any parent element that you want to treat as a drop down
element. In my case, I have used a div element. You can even make an li element as "dropdown". Then
you have to place an <a> tag immediately inside the dropdown element. Add a new attribute "data-tog-
gle" to the link tag and give the value as "dropdown". Finally add a ul list below the link tag. You have to
add class as "dropdown-menu" to the ul tag. To add a separator between li elements, add a new empty li
element with class as "divider" to the list. if you are not comfortable with the data-* attributes then you
Bootstrap: A SitePoint Anthology - 31
can even trigger drop down using jQuery. Give a unique id to the link element and call the dropdown
method as below:
$('#myDropDown').dropdown();
ScrollSpy
ScrollSpy is an interesting JavaScript module added to the Bootstrap library. It is basically a combination
of navigation menu and contents below. Its role is to update the active item in the navigation bar as you
scroll down the content area. To use the ScrollSpy feature you have to add data-spy="scroll" and
Scrollspy
Tabs
Bootstrap 3s tabs take inspiration from traditional jQuery tabs. They both look and function alike. To
use Bootstrap Tabs you need to define two separate sections: the tabs navigation and tab areas. The
markup goes like below:
<!-- Nav tabs -->
<ul class="nav nav-tabs">
<li class="active"><a href="#home" data-toggle="tab">Home</a></li>
<li><a href="#profile" data-toggle="tab">Profile</a></li>
<li><a href="#messages" data-toggle="tab">Messages</a></li>
<li><a href="#settings" data-toggle="tab">Settings</a></li>
</ul>
<!-- Tab panes -->
32 - Bootstrap: A SitePoint Anthology
<div class="tab-content">
<div class="tab-pane active" id="home">...</div>
<div class="tab-pane" id="profile">...</div>
<div class="tab-pane" id="messages">...</div>
<div class="tab-pane" id="settings">...</div>
</div>
The navigation is created using a ul element with the class nav-tabs while the additional class nav
is used to apply the navigation CSS style. Each li element is composed of an internal link that should
define the attribute data-toggle as tab. This triggers Bootstraps Tabs JavaScript and the respective
tab area is displayed. Coming to the tabs area, it consists of a set of div elements. The parent div should
have a class as tab-content and the child divs should have a class tab-pane. Each tab-pane must
have an id corresponding to the internal links defined in the tabs navigation. In the above example, I
have set a class of the first tab-pane as active. This makes it visible by default.
ToolTip
ToolTip is an extremely useful JavaScript plugin provided by Bootstrap 3. It helps in showing help texts
on any HTML element. It's cross-browser compatible, too! To use ToolTip, the markup goes like this:
<button id="myButton" type="button" class="btn btn-default"
data-toggle="tooltip" data-placement="left" title=""
data-original-title="Tooltip on left">Tooltip on left</button>
The above markup displays a button with the tooltip feature. Attribute data-toggle is used by Bootstrap to identify on which element it has to display the tooltip. Attribute data-original is used to
define what goes inside the tooltip. Attribute data-placement is used to help bootstrap where to show
the tooltip. For performance reasons, Bootstrap will not initialize the ToolTip and Popover components
by default. You have to initialize them manually by using the following jQuery:
$('#myButton').tooltip();
Popovers
Bootstrap: A SitePoint Anthology - 33
If you have ever been a hardcore iBook reader, then you would understand what popovers are. They are
the extended version of ToolTip with some more functionalities. You can display more HTML elements
The HTML snippet displays a button with popover functionality. It also has set of custom data-*
attributes that you must necessarily understand. Attribute data-toggle identifies which element must
control the popover. Attribute data-content contains the data that should be displayed inside the
popover. Attribute data-placement tells on which side should the popover appear. In the above case,
the data must be plain text only. If you want to display HTML content inside the popover, then you have
to add the additional attribute data-html as true. The HTML data-content must go inside the double
quotes with escaped characters wherever necessary. The markup for the HTML data contents inside the
popover should be like below:
Alerts
Alerts in Bootstrap are not like window popups. They are a set of divs with predefined background
The above alert has a pale yellow background, since it is a warning message. You can change the color to
red by changing the class of the alert to alert-danger. Every alert div must have a close button with a
set of data-* attributes as defined above. Attribute data-dismiss hides the alert div when clicked.
Conclusion
You might now have a better understanding of how Bootstrap helps us using JavaScript components
without writing a single line of jQuery in our code. These JavaScript components are one of the main
reasons why the Bootstrap framework is so popular in the web today.
Preprocessors like Less, Sass, Stylus, etc., extend the capabilities of CSS by including such programming
language features as variables, functions, mathematical operations, etc. Appropriate use of this technolo-
This article takes a step beyond the basics of the Less preprocessor language by using some of the
Bootstrap 3 Less code as both a learning and development tool.
If you're just starting out, enjoy Speed Up Your Web Development Process with Less, a clear and concise
so that you can freely see how the page looks, check the code details for yourself and experiment with it.
Folder structure
}} All the Bootstrap files go into the bootstrap folder. This also includes a mixins folder where we
}} The demo.css file will be added to the css folder, once the Less files are compiled.
}} The project's Less file, demo.less, is placed inside the less folder. All the Less code I write for
and JavaScript plugins are not used. But don't be fooled - there's enough in there to show the Bootstrap's
mixins goodness in action:
}} adaptive layout
}} nested columns
}} columns offset
Desktop view
</main>
</div>
</div>
Here's an added bonus of using the Less source code: a clean HTML document without any typical
Bootstrap grid classes.
The files listed below need to be copied over from the Less folder of the downloaded source code into
the demo's bootstrap folder:
}} mixins.less
}} normalize.less
}} scaffolding.less
}} variables.less
Bootstrap folders
Also, the entire content of the mixins directory of the Bootstrap source code needs to be copied over into
the demo's mixins folder.
The Compiler
You can compile Less code both server side and
client side.
Mixins folder
document.
Client side compiling is great to get started with Less and experimenting with it. However, for a production site, the best option is server side precompiling with node.js or a third party tool.
This demo uses Prepros, a precompiler for Windows, Mac, and Linux available both as a free and a paid
download. You're free to use your favorite tool, it won't affect the end result.
For an in-depth guide on how to use Prepros to precompile your Less code, Multilingual Preprocessing
with Prepros by Ivaylo Gerchev will tell you all you need to know.
Mixins are a way of including ("mixing in") a bunch of properties from one rule-set
into another rule-set.
Here's an example. If we choose to build a web layout using floats, we will need a technique to clear
those floats.
Below is the Clearfix Hack by Nicolas Gallagher, also used by the Bootstrap framework, turned into a
Less mixin.
.clearfix() {
&:before,
&:after {
content: " ";
display: table;
}
&:after {
clear: both;
}
}
The advantage of having it packaged into a mixin is that we can now add it wherever we need to clear
floats with just one line of code. For example, here's how to add it to a container element that encompasses a number of floated elements:
.container {
property1: value1;
property2: value2;
.clearfix();
}
42 - Bootstrap: A SitePoint Anthology
The level of complexity of a mixin varies in relation to what you intend to achieve with it. It's time to see
what it's possible to achieve using the Bootstrap mixins as a library for our project.
excellent mixins library not only helps you write awesome CSS code, but is also a great way to learn
from the best. Let's open the mixins folder and explore the way Bootstrap builds its Less code.
Layout Mixins
The mixins that I personally find most useful are those that help me build the page layout. You can find
these in grid.less.
(@gutter / 2);
&:extend(.clearfix all);
}
gives us quite a bit of flexibility. We can use the same ruleset but customize it differently by changing the
This particular Bootstrap mixin uses arguments with default values. The argument @gutter has a
default value of @grid-gutter-width, that you can find in the variables.less file. This means
that, if no value for this argument is passed when using the mixin, the code will fall back on the default
value.
One more interesting bit to notice about the .container-fixed() mixin is its use of &:extend(.
clearfix all).
}} it extends that functionality to the elements and classes styled using the
}} by adding the "all" keyword at the end, it ensures that the compiler extends the clearfix
functionality to all selectors nested inside the extended class.
Since the release of version 3.1.0 of the Bootstrap framework, &:extend(.clearfix all) has
replaced the use of the .clearfix() mixin inside the .container-fixed() mixin (you can define
a mixin inside another mixin). Let's examine why we can consider this move as an improvement in the
Applying the .clearfix() mixin to any element or class that contains floated children ends up
repeating the same clearfix hack over and over in the CSS document.
What the Less ":extend()" pseudo-class does is to produce a CSS declaration that groups together all the
elements and classes that share the same CSS rules. For instance, if you were to apply the .clearfix()
mixin to .container, .row, and .footer, your compiled CSS would repeat the same clearfix hack for
However, using the Less :extend() pseudo-class instead, as Bootstrap now does, will output this CSS
code:
.container:before,
.container:after,
.row:before,
.row:after,
.footer:before,
.footer:after {
display: table;
content: " ";
}
.container:after,
.row:after,
.footer:after {
clear:both;
}
The gain of using the :extend() pseudo-class is a compliance with the DRY principle. In particular, it
avoids repeating the same CSS code by merging together elements and class selectors that share the
same bunch of properties.
To use the Bootstrap .container-fixed() mixin in your code, add .container-fixed() to a class
or a HTML element. In this article's demo, I use it for the .container class, just like Bootstrap does:
.container { .container-fixed(); }
Here's what the CSS output of the .container class looks like:
.container {
margin-right: auto;
margin-left: auto;
padding-left: 15px;
padding-right: 15px;
}
ates the styles for this element. Here's what it looks like:
.make-row(@gutter: @grid-gutter-width) {
margin-left:
(@gutter / -2);
This mixin calculates a left and right margin for the row. Also, since the .make-row() mixin is designed
to style wrappers for floated columns, it's extended with the .clearfix class for floats clearing.
Each column size is generated by a corresponding mixin. Because these mixins have a similar pattern,
let's just examine the mixin for the medium column.
(@gutter / 2);
This is another parametric mixin. The @gutter argument has a default value, but the value for the @
columns argument will have to be provided when using the mixin. If you don't assign a value to the
@columns argument, Less will throw an error.
A great feature Less offers is nesting. You can nest selectors in a way that reflects the parent-children
relationship in your HTML document, without having to write the parent's selector every time you
reference a child element's selector.
The Bootstrap .make-md-column() mixin shows us how to take advantage of this nifty Less feature
inside a mixin. The LessCss website says:
Directives such as media or keyframe can be nested in the same way as selectors.
Directive is placed on top and relative order against other elements inside the same
ruleset remains unchanged. This is called bubbling.
The media query inside the .make-md-column() mixin dictates the column's behavior when the
screen's width corresponds to the value of the @screen-md-min variable (Bootstrap gives a default
value of 992px to this variable. You can find this out in variables.less). When the screen's width hits
the assigned value, the column's width will be equal to the percentage value of your design's number
of columns divided by the total number of columns (Bootstrap's default value for the total number of
columns is twelve).
The demo uses the .make-md-column() mixin for the sidebar, the main content column, and the six
nested columns inside the main content.
.sidebar {
.make-md-column(4);
}
.main-content {
.make-md-column(12);
}
.card {
.make-md-column(5);
}
The .button-variant() mixin is located in the buttons.less file inside the mixins folder. It
outputs default button styles, as well as styles for common button states. This means that you add this
mixin to a button element's selector and never worry about writing other rules for all those button states.
This parametric mixin needs three values from you and spits out a major chunk of CSS code that covers
all buttons' states.
There are some selectors that are part of the Bootstrap framework in there, like .badge or
.dropdown-toggle. But nothing prevents you from copying over this mixin into demo.less (or into
your project's specific mixins library folder) and customizing it to fit your own needs. If you didn't want
any extraneous Bootstrap selectors, you could rewrite the .button-variant() mixin like so:
.demo-button-variant(@color; @background; @border) {
color: @color;
background-color: @background;
border-color: @border;
&:hover,
&:focus,
&.focus,
&:active,
&.active {
color: @color;
background-color: darken(@background, 10%);
border-color: darken(@border, 12%);
}
&:active,
&.active {
background-image: none;
}
&.disabled,
&[disabled],
fieldset[disabled] & {
&,
&:hover,
&:focus,
&.focus,
&:active,
&.active {
background-color: @background;
border-color: @border;
}
}
}
fieldset[disabled] .action-btn:active,
.action-btn.disabled.active,
.action-btn[disabled].active,
fieldset[disabled] .action-btn.active {
background-color: #b0e1ef;
border-color: #31b0d5;
}
What about all those ampersand symbols (&)? The ampersand selector refers to the parent selector
inside a nested selector. The most common use is with pseudo-classes, like in the example below. Instead
of repeating .action-btn like in vanilla CSS, slamming an ampersand does the job and saves precious
time.
.action-btn {
color: gray;
&:hover {
text-decoration: none;
}
}
You can also use the ampersand selector inside mixins, like in the Bootstrap .button-variant()
mixin. When the ampersand is placed at the end of the selector list, it allows you to reverse the order of
nesting. To use a small chunk of the .button-variant() mixin as example:
...
}
When the mixin above is used on the .action-btn selector, it outputs the following CSS
.action-btn:active,
.action-btn.active,
.open > .dropdown-toggle.action-btn {
background-image: none;
}
Gradients Mixins
In gradients.less inside the mixins folder, you'll find a bunch of mixins encapsulated within a namespace.
This is a great technique for grouping mixins for organizational purposes and making your code more
portable.
Here's the general structure of the Bootstrap gradient mixin to illustrate this point (the complete source
code is available with the demo's files).
#gradient {
.horizontal(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent:
100%) {
//mixin's code goes here
}
.vertical(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent:
100%) {
//mixin's code goes here
}
.directional(@start-color: #555; @end-color: #333; @deg: 45deg) {
//mixin's code goes here
}
...
}
As you can see, namespaces are defined in the same way as CSS ID selectors.
In the example above, the code that goes inside each grouping is not different from what you would
write in your CSS code for a gradient, only using the mixin's arguments instead of fixed values.
In the demo for this article, I use the vertical gradient mixin to style the background of the entire web
page:
body {
#gradient > .vertical(lighten(@brand-primary, 40% ); lighten(@brand-primary, 60%) );
}
The Bootstrap gradient mixin has default values as arguments, therefore you can just use empty brackets
and it works. Here, I change the start and end color of the gradient using the Less pre-built lighten()
and darken() color functions.
Less has a great variety of color functions. The ones used above are designed to produce a lighter or
darker variant of the input color. Really handy when you need a quick way of generating a palette of
different shades of the same basic color value.
Conclusion
In this article I've highlighted some features of the Less preprocessor language by getting close and
personal with the Bootstrap mixins and using a good number of them in a small project.
Exploring and using Bootstrap as a rich mixins library means translating all the theory on the Less
preprocessor language we gain from books, courses, and tutorials, into a real-world context. It's a great
way of making the transition from handling the basics of Less to becoming a pro.
If you tried using Masonry together with the Tabs widget, one of the many JavaScript components
Bootstrap has to offer, chances are youve stumbled on some kind of annoying behavior. I did, and this
article highlights what the issue is and what you can do to solve it.
of content panels. On page load, the first panel has the class .active applied to it. This enables the
panel to be visible by default. This class is used via JavaScript to toggle the panels visibility via the
events triggered by the tabbed navigation links: if .active is present the panel is visible, otherwise the
panel is hidden.
If you have some web content thats best presented in individual chunks, rather than crammed all in one
spot, this kind of tabs component might come in handy.
Why Masonry?
In some cases, the content inside
each panel is suited to being
appears broken.
ghastly gaps.
Each grid item inside the tab panels is built with the Bootstrap grid system and the Bootstrap Thumbnails component. Heres a code snippet to illustrate its structure:
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="http://lorempixel.com/200/200/abstract" alt="">
<div class="caption">
<h3>Thumbnail label</h3>
<p>...</p>
<p>
<a href="#" class="btn btn-primary" role="button">Button</a>
<a href="#" class="btn btn-default" role="button">Button</a>
</p>
</div>
</div>
</div>
<!-- Repeat two more times ... -->
The code above builds a three-column grid on large to medium screens and a two-column grid on
smaller screens. If you need a refresher on the Bootstrap grid system, Understanding Bootstraps Grid
System by Syed Fazle Rahman is a great read.
The Tabs widget in the demo page has the following HTML structure:
<div role="tabpanel">
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">
<a href="#panel-1" aria-controls="panel-1" role="tab" data-toggle="tab">Panel 1</
a>
</li>
<li role="presentation">
<a href="#panel-2" aria-controls="panel-2" role="tab" data-toggle="tab">Panel 2</
a>
</li>
<li role="presentation">
<a href="#panel-3" aria-controls="panel-3" role="tab" data-toggle="tab">Panel 3</a>
</li>
58 - Bootstrap: A SitePoint Anthology
<li role="presentation">
<a href="#panel-4" aria-controls="panel-4" role="tab" data-toggle="tab">Panel 4</a>
</li>
</ul>
<!-- Tab panels -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="panel-1">
<div class="row masonry-container">
<div class="col-md-4 col-sm-6 item">
<!-- Thumbnail goes here -->
</div>
<div class="col-md-4 col-sm-6 item">
<!-- Thumbnail goes here -->
</div>
<div class="col-md-4 col-sm-6 item">
<!-- Thumbnail goes here -->
</div>
...
</div><!--End masonry-container
</div><!--End panel-1
-->
-->
-->
...
</div><!--End tab-content
</div><!--End tabpanel
-->
-->
Here are a few things to note about the code snippet above:
}} HTML comments point to the Tabs key components: Nav tabs marks the tabbed navigation
attribute, which is the same as the value of the id attribute of the content panel. For
}} The tabbed links connect to the corresponding content panel through the value of their href
instance, the link with href="#panel-1" opens the content panel with id=panel-1.
}} Each anchor tag in the navigation section includes data-toggle="tab". This markup enables
apply to the wrapper div element that encompasses all the grid items and a class of
}} Finally, the elements that Masonry needs to target have a class of .masonry-container that
To see the full power of the Masonry library, make sure the grid items are of varying heights. For
instance, delete the image on one item, shorten a paragraph on another, etc.
For the full code, check out the code panels in the CodePen demo.
To avoid layout issues, the librarys author recommends using Masonry together with the imagesLoaded
plugin.
Masonry doesnt need the jQuery library to work. However, because the Bootstrap JavaScript components already use jQuery, Ill be making life easier for myself and initialize Masonry the jQuery way.
Heres the code snippet we need to initialize Masonry using jQuery and imagesLoaded.
var $container = $('.masonry-container');
$container.imagesLoaded( function () {
$container.masonry({
columnWidth: '.item',
itemSelector: '.item'
});
});
The code above caches the div that wraps all the grid items in a variable called $container.
Next, Masonry is initialized on $container with a couple of recommended options. The
columnWidth option indicates the width of a column of a horizontal grid. Here it is set to the width of
the single grid item by using its class name. The itemSelector option indicates which child elements
are to be used as item elements. Here, its also set to the single grid item.
Its now time to test the code.
First, it seems fine because the grid inside the default active tab panel is displayed correctly:
However, if you click on a tabbed navigation link to reveal the hidden panels content, heres what
happens:
Peeking inside the source code reveals that Masonry has fired as expected, but the position of each item
is not being calculated correctly: grid items are all stacked on top of each other like a pack of cards.
And thats not all. Resizing the browser window causes the grid items to position themselves correctly.
}} show.bs.tab fires on tab show, but before the new tab has been shown.
}} shown.bs.tab fires on tab show after a tab has been shown.
}}
hide.bs.tab fires when a new tab is to be shown (and thus the previous active tab is to be
hidden).
}} hidden.bs.tab fires after a new tab is shown (and thus the previous active tab is hidden).
62 - Bootstrap: A SitePoint Anthology
Because the grid layout gets messed up after a tab has been shown, we go for the shown.bs.tab event.
Heres the code, which we place just below the previous snippet:
$('a[data-toggle=tab]').each(function () {
var $this = $(this);
$this.on('shown.bs.tab', function () {
$container.imagesLoaded( function () {
$container.masonry({
columnWidth: '.item',
itemSelector: '.item'
});
});
});
});
finished loading.
Conclusion
In this article Ive shown how to integrate Bootstraps Tabs component with the Masonry JavaScript
library.
Both scripts are easy to use and quite powerful. However, put them together and youll face some
annoying layout bugs affecting the hidden tabs. As shown above, the trick is to re-initialize the Masonry
library after each panel becomes visible.
With this solution in your toolbox, achieving great tiled layouts will be a breeze.
By Rhiana Heath
@rhianaheath
Application accessible, I ran into a few problems. As Bootstrap is mainly used for design I evaluated how
accessible their base design was for people with visual impairments in terms of the colors. But first a
quick recap.
What Is Bootstrap?
Bootstrap site
Bootstrap is a popular tool for creating front-end websites and web-applications. It contains HTML, CSS,
and optional JavaScript extensions which can be added to your website to style and add functionality. It
is estimated that as many as 4.7 million websites, or 1.79% of all websites, use Bootstrap.
It is also the number one project on Github with developers encouraged to contribute to the source code.
Bootstrap is quick to set-up, ships with copious documentation and easy-to-follow instructions on how
The Bootstrap team are continually releasing new versions and updates, and in their they have promoted several accessibility-focussed features in their most recent version release (3).
But how accessible is Bootstrap really? Before we can tackle that, I think we need to define what we
mean by 'accessible'.
can be easily used by people with disabilities. This can include many different types of impairments
with a wide range of severity, however the main four types of disability referred in the Web Content
2. Hearing impairments
3. Motor impairments
4. Intellectual disabilities
referred to by the acronym 'POUR': Perceivable, Operable, Understandable and Robust. Color choices
comes under the 'Perceivable' column for Web Accessibility. That is, the content on the website should be
easy to see. In particular, text and images should be easy to discern against their background with a high
ways. Some may need to have the screen zoomed in, some may need to have the color settings changed
to high contrast and others will also require the help of a screen reader or Braille reader.
different way.
Photo: entirelysubjective
late what it would like like for different levels of color blindness, and if it has enough contrast for that as
well. From the Bootstrap site I tested their links, progress bars, navigation bars and their alerts to see if
they were a high enough ratio for accessibility.
Taking into account their font-size and font-weights as per the contrast guidelines in the table below.
Text
Normal
Small < 24px
Large > 24px
Bold
< 19px
> 19px
Ratio AA
4.5:1
3:1
Ratio AAA
7:1
4.5:1
For example when testing their very common Bootstrap Blue color used in links, progress bars and
navigation bars. When these were put into the checker below shows that this scheme meets the require-
ments only if the text is of large size. However the text shown is 14px and normal font-weight, which is
a {
color: #428bca;
text-decoration: none;
}
a {
color: #3277b3;
text-decoration: none;
}
They have made some progress, for example the alerts in their previous version 2, the ratios varied from
3.3:1 to 3.9:1, just below the minimum of 4.5:1. Which would be required as this text is 14px, so classified
as small text. In the new version 3, with a very slight change, all ratios are now above 4.5:1. With this
little change they were able to comply with guidelines, without having to compromise the design. This
was after someone noticed it and raised an issue on their GitHub repository requesting them to address
this.
I have spent a lot of time then going through and manually changing the colors in Web Applications so
they meet this requirement. Alternatively the font-size and weight could be changed so it is classified as
large text. I forked the Bootstrap Repository and updated their code with the changes I made. This can
be downloaded and used instead of the standard one or used as a reference point as you may want to
make your own which suit your scheme and also meet the color contrast ratio requirements.
background which can be easier to see for people with partial blindness. In Chrome there is a plugin to
Both Windows and Mac's have a high contrast mode in their desktop settings, which will show the
entire screen in high contrast. In Firefox this involves going into the settings, preferences, content and
colors, changing the text to white, the background to black then un-ticking the following option.
Firefox settings
The high contrast test yielded some varying results. This is a common test during an accessibility audit.
The most unforgiving combination seems to be Firefox in Windows, so most of my testing was using this
browser/operating system as it is also a very popular combination for people with visual impairments
to use.
However testing in as many combinations of browsers and operating systems as possible is ideal as they
all render slightly differently. One of the major problems I found was that bootstrap buttons either have
very faint text under high contrast or none at all (with Firefox in Windows). I found this was due to the
background-color property in CSS.
.btn-default {
color: #333;
background-color: #fff;
border-color: #ccc;
}
Once the background-color was removed completely it was much easier to see under high contrast, see
below. Another area where this was affected were text inputs. The same sort of principle applied, they
Which means under high contrast you cannot make out the text you are typing. However after you
remove this one line of CSS the visibility significantly improves in this mode with no visual difference
for sighted users.
However this introduces a new problem: how to maintain the color for sighted users, however not using
background-color in order to have it display in high-contrast settings. In Bootstrap 2 I found this was no
problem as there were other CSS properties to control the look of the button, so removing the back-
ground-color had no visual impact to sighted users -- a 'win-win' there. In the custom GitHub repository
mentioned, I've removed the background-color and replaced it with the CSS used in previous versions,
slightly modified to meet the color contrast ratio and are also now visible in high contrast.
Keep in mind, I only noticed this issue in Firefox. When checking this with high contrast in Chrome for
example these buttons and inputs displayed fine. One thing that didn't though were Bootstraps inverted
navbars. Ordinarily they look like this below.
However in high contrast mode in Chrome it becomes unreadable. This is due largely to the color
contrast ratio between the links and background not being high enough, making it disappears in this
mode. The background would need to be darker or the links lighter. However even then it is difficult to
see with this tool, so perhaps it's wiser to avoid just this color combination if possible.
pure color palette choices, most components were tested, and unfortunately not many of them passed
the color contrast ratio tests or high-contrast readability settings.
Three Tips
1. Keep using Bootstrap in your website or application -- but keep it's accessibility blind-spots in
mind.
2. Always upgrade to newer versions whenever possible as they do keep incrementally improving.
3. Feel free to use or reference the modified Bootstrap CSS file on GitHub instead of the standard
one. Paypal also provides an accessibility plug-in for bootstrap which handles a lot of issues
If you find anything else, please take a moment to raise an issue with Bootstrap on their GitHub page,
definitely submit code which would address the problem. Otherwise perhaps look into using a front-
end framework that has accessibility features already included. While they're aren't many out there yet
Accessible Template offer one and their site is an fantastic example best accessibility practices.
effects to the Bootstrap Carousel, while still making sure this handy JavaScript component remains
bloat-free and quick to implement.
Introducing Animate.css
74 - Bootstrap: A SitePoint Anthology
As rewarding as crafting my own animation effects can be, Im going to use a well-known open source
CSS3 animation library most aptly called Animate.css, by Dan Eden.
This is so that I can focus on the task at hand, rather than on explaining the code for CSS3 animations. However,
if you want to delve into that topic, youll enjoy the CSS3 Animations series here on SitePoint, by Craig Buckler.
2. Add the classes of animated yourchosenanimation to the elements you intend to animate
on your web page.
In the latter step you would replace yourchosenanimation with the class name corresponding to any
of the numerous animations you see on the Animate.css website.
position the slide currently being viewed occupies, and offer an alternative navigation for the slider.
}} The Carousel item, located inside a wrapper container with a class of .carousel-inner,
represents each individual slide. Its inside each item that you place your images. You can also add
captions to your slides. The nice thing is that you can put pretty much any HTML element inside
a container with the class of carousel-caption and Bootstrap will take care of the styling and
formatting. Its these captions that were going to animate.
}} Finally, the Carousel controls are the navigation arrows that enable users to access the next and
previous slides.
If youd like to explore the Bootstrap Carousel component in detail, be sure to check out Creating
JavaScript Sliders Using Bootstrap 3, by Syed Fazle Rahman.
To keep this demo simple, Im not going to add images to the carousel. The focus is all on the carousel
captions as the object of our animations.
}} A custom stylesheet and JavaScript document (both of which we will edit in this article)
To speed up the process, grab a starter template from the Bootstrap website and add the necessary files.
Heres the code for the Bootstrap Carousel:
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active">
</li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<!-- First slide -->
<div class="item active">
<div class="carousel-caption">
<h3 data-animation="animated bounceInLeft">
This is the caption for slide 1
</h3>
76 - Bootstrap: A SitePoint Anthology
role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-example-generic"
role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div><!-- /.carousel -->
If youve included the correct files and you open the above code in your browser, you should be able to
see a nice working carousel, and all this without writing a single line of JavaScript. If you didnt add any
images to the carousel, just assign a min-height value to the .carousel .item selector in your CSS
The elements inside the carousel caption that well be animating have a data-animation attribute
added to them with the specific animation class name as their respective value.
If youd like to experiment with other animations from the Animate.css library, feel free to replace the
values in the data-animation attribute with your chosen animation class names.
Well be using the data-animation attribute in our JavaScript code shortly.
Although a simple auto-playing carousel is what you could be looking for in some cases, for this demo
were after more control.
As a first step in this direction, delete the data-ride="carousel" attribute from the .carousel
element. The data-ride attribute initializes the carousel without having to write any JavaScript code.
However, were going to take control of the carousel using JavaScript, therefore the data-ride attribute
wont be necessary.
rules that Im going to focus on here are those relevant to the smooth working of this demo.
More specifically, were taking control of the animation-delay property, which will define when each
animation will start (note that vendor prefixes are omitted for brevity).
.carousel-caption h3:first-child {
animation-delay: 1s;
}
.carousel-caption h3:nth-child(2) {
animation-delay: 2s;
}
.carousel-caption button {
animation-delay: 3s;
}
The snippet above ensures that the elements start their animation sequentially. Theres room for play
here. For instance, you can choose to start animating the first two headings at the same time, followed by
browser. However, to animate subsequent slides as they come into view, our code will have to fire on the
slide.bs.carousel event. This means that the same code will be used twice: on page load and on the
slide.bs.carousel event.
Because we love the DRY ("Don't Repeat Yourself") principle, were going to wrap our code in a function
function doAnimations(elems) {
var animEndEv = 'webkitAnimationEnd animationend';
elems.each(function () {
var $this = $(this),
$animationType = $this.data('animation');
// Add animate.css classes to
// the elements to be animated
// Remove animate.css classes
// once the animation event has ended
$this.addClass($animationType).one(animEndEv, function () {
$this.removeClass($animationType);
});
});
}
// Select the elements to be animated
// in the first slide on page load
var $firstAnimatingElems = $myCarousel.find('.item:first')
.find('[data-animation ^= "animated"]');
// Apply the animation using our function
doAnimations($firstAnimatingElems);
// Pause the carousel
$myCarousel.carousel('pause');
// Attach our doAnimations() function to the
// carousel's slide.bs.carousel event
$myCarousel.on('slide.bs.carousel', function (e) {
// Select the elements to be animated inside the active slide
var $animatingElems = $(e.relatedTarget)
.find("[data-animation ^= 'animated']");
doAnimations($animatingElems);
});
Theres quite a lot going on in the chunk of code above, so lets break it down.
each time the animation ends, we remove the Animate.css classes. If we fail to do this, the carousel
captions will be animated only once, that is, just the first time the carousel shows a particular slide.
var animEndEv = 'webkitAnimationEnd animationend';
Next, our function loops over each element that we want to animate and extracts the value of the
data-animation attribute. As you recall, this value contains the Animate.css classes that we need to
add to our element in order to animate it.
elems.each(function () {
var $this = $(this),
$animationType = $this.data('animation');
// etc...
});
Finally, the doAnimations() function dynamically adds the Animate.css classes to each element that
we want to animate. It also attaches an event listener that fires only once, when the animation ends.
After the animation ends, the Animate.css classes that we just added are removed. This ensures that the
next time the carousel comes back to the same slide, the animations take place again (try removing this
bit of code and youll see the animations happen only once).
$this.addClass($animationType).one(animEndEv, function () {
$this.removeClass($animationType);
});
.find("[data-animation ^= 'animated']");
doAnimations($firstAnimatingElems);
Int this code, we begin by finding the first slide. From there, we select the content we want to animate
inside the caption by using the values of the data-animation attribute starting with animated. We
then use the piece of data thus obtained as an argument in our doAnimations() function and let the
This is a feature of the Bootstrap Carousel designed to stop it from cycling. Youre free not to pause the
carousel, but you run the risk of annoying your website visitors.
In this case, I recommend you make sure the carousel doesnt cycle to the next slide until all animations
on the active slide have run their course. You can control this by setting the interval option in the
initialization code as follows:
$myCarousel.carousel({
interval: 4000
});
I my opinion, an infinitely looping carousel with captions jumping around each time a slide comes into
This event fires immediately when the slide instance method is invoked.
$myCarousel.on('slide.bs.carousel', function (e) {
// do stuff...
});
Next we select the active slide, that is, the slide currently in view, and from there we find the elements
we wish to animate. The code below uses the .relatedTarget property of the slide.bs.carousel
event to get hold of the active slide.
Finally, we call our doAnimations() function, passing our selection of the elements to be animated as
an argument.
doAnimations($animatingElems);
Conclusion
As many of you probably know, Carousels do have issues that developers need to take into consideration.
With the Bootstrap Carousel component adding a slider or carousel to a web page is just a matter of
entering the appropriate HTML markup.
In this article, Ive shown how to add some extra pizzazz to the basic Bootstrap Carousel component
with a few lines of jQuery and the Animate.css library. However, any other similar CSS library, or coding
the CSS3 animations from scratch, will do just as well.
By Reggie Dawson
@ReggieWrites
bootstrap-sass. If you are not familiar with Bootstrap implementing the Sass version can be a little tricky.
In this article I will show you how to configure and customize Bootstrap with Sass.
It is worth noting that the upcoming version of Bootstrap, Bootstrap 4, will use Sass by default. Until it's
released, unless you want to use the alpha version versions of bootstrap 4, you'll need to use bootstrap-sass.
84 - Bootstrap: A SitePoint Anthology
Installation
There are multiple ways to obtain and install bootstrap-sass.
Download
You can download bootstrap-sass from the Bootstrap download page. Once you have it downloaded
extract the contents of the file to the folder you are going to create your project in.
Compass
If you are using Compass then you'll have Ruby installed. With Ruby installed we can use gems, in this
If you have an existing Compass project and want to add bootstrap-sass, run this command:
compass install bootstrap -r bootstrap-sass
Bower
We can also install it with the package manager Bower. To me this option is the best as the other options
install a lot of 'fluff' that will confuse someone not familiar with Bootstrap. To install with Bower make
sure you are in the folder where you want to create your project and run:
bower install bootstrap-sass
Configuration
Once we have installed our desired version of bootstrap-sass we need to configure our project. The type
of install we performed will determine where the files we need are located.
Download
The download includes a lot of folders that we will not need if we aren't using Rails. The only folder we
need is the assets folder. We can copy the contents of this folder to the root of our project or use it as is. If
you intend to use Javascript components you will have to manually download jQuery.
Compass
Using the Compass version creates a styles.scss and _bootstrap-variables.scss file. Folders
for fonts, javascript, sass, and stylesheets are created. The important thing to note is that styles.scss
imports Bootstrap as a whole, there is no way to pick and choose what Bootstrap components you want
Bower
An install from Bower includes everything you need for Bootstrap, even jQuery. All components
installed are located in the bower_components directory.
Setup
Once we have Bootstrap installed we need to setup our project to use it. The first thing we want to do is
create folders for sass and stylesheets (the Compass setup has already created these). The sass folder
will hold our scss files while stylesheets will be where compiled css will be stored. After that create a
file named app.scss inside the sass folder. If we are using Compass this file has already been created as
styles.scss.
The app.scss file (or styles.scss in Compass) is used to import bootstrap components. For
example:
Download
@import "bootstrap-sass-3.3.4/assets/stylesheets/bootstrap";
Compass
@import "bootstrap";
Bower
@import
"../bower\_components/bootstrap-sass/assets/stylesheets/bootstrap";
The next thing we want to do is navigate to the Bootstrap folder and find the stylesheets folder. Inside of
stylesheets there is a bootstrap folder. Copy the _variables.scss file to your sass folder. Rename
app.scss. Make sure to import _customVariables.scss first for reasons I will explain in a moment.
If you are using Compass you can skip this step as the _bootstrap-variables file serves the same
purpose. The file has already been imported into styles.scss for you. If you are using Compass with
Bower it is advisable to import bootstrap-compass.scss.
The last import is an optional _custom.scss file. Many people will include custom css rules directly
after their import statements or in their app.scss file, but I prefer to separate any custom rules into
their own partial. At any rate our app.scss should have three import statements now (or four if using
Compass).
@import "customVariables";
@import "../bower\_components/bootstrap-sass/assets/stylesheets/bootstrap";
@import "../bower\_components/bootstrap-sass/assets/stylesheets/bootstrap-compass";
@import "custom";
Notice we import our _customVariables.scss file first. The reason being is all of Bootstrap's
variables are set to default! values,so we need to override these values by importing our variables first.
Customize
When we edit variables it is advisable to make a copy of the original and change the copy. After copying,
comment out the original variable. That way we can go back to what it was previously set to in case we
don't like the result. For example lets say we wanted to change the base font size to 20px. First we will
look in our _customVariable.scss file. The variables are broken down by section, we are looking for
the Typography section. There we want the $font-size-base:14px !default; variable. Copy and
paste and comment out the original. After that it is as simple as changing the value to 20px.
$font-size-base:14px !default;
$font-size-base:20px !default;
As you can see I have commented out the original variable and changed the copy.
Bootstrap: A SitePoint Anthology - 87
When trying to customize Bootstrap bear in mind there are a lot of variables to deal with. When looking
for a variable to change it is advisable to make full use of your text editors search feature. It is also a
good idea to look over the _customVariables.scss file and get familiar with the variables present.
Another effective method for finding what variables you need to change is to look at the raw scss files
that make up Bootstrap before they are compiled. From there we can see what variables are used in that
module. For example lets say I am not happy with the color of the .navbar-default element. Instead
of me trying to figure out what variable I need to change I can look inside of the _navbar.scss file. I
scroll down (or use my search function) to find a reference to a color variable.
// Default navbar
.navbar-default {
background-color: $navbar-default-bg;
border-color: $navbar-default-border;
.navbar-brand {
color: $navbar-default-brand-color;
&:hover,
&:focus {
color: $navbar-default-brand-hover-color;
background-color: $navbar-default-brand-hover-bg;
}
}
From looking at this rule I determine the variable I need to change is $navbar-default-bg. I would
then go into my _customVariables.scss and copy/comment out original variable and create my
own.
When using bootstrap-sass you also have the advantage of being able to use and look at the mixins
included with Bootstrap. My first article for Sitepoint was about 5 useful mixins in Bootstrap, so it's no
secret I am a fan of the Bootstrap mixins. Not only will they help with understanding how Bootstrap fits
together, they may actually help you build your site. For example looking at @mixin make-row:
@mixin make-row($gutter: $grid-gutter-width) {
margin-left:
($gutter / -2);
From this mixin we can see what variables affect our row. We now know we can alter the
$grid-gutter-width to make changes to the margins of a row. Also we see that the clearfix mixin
has been included. We can also look that over to see what that affects.
Conclusion
Using Bootstrap can be complicated especially for someone that is not familiar with the framework. With
the methods I demonstrated you should be able to get Bootstrap setup with Sass and customize the
framework with ease. Finding the variables you need to change should be more manageable now that
you know what to look for. Just remember your text editors search functions are your friend, and when
in doubt looking at the mixins can help.
developer. For this reason, more and more developers are including
the framework in their personal toolbox.
By Brad Barrow
@foxwisp
In this article, Ill explain how you can use Bootstrap in a more robust and semantic way. Bootstraps
latest version shipped with an official Sass port of the framework so well use one of Sasss most
powerful features to achieve this: the @extend directive.
documents are intended to be descriptive of their contents from an information hierarchy perspective.
One should be able to read them and know what they are about, not how they will look.
With the rise in popularity of CSS and especially CSS frameworks, HTML is often written with a CSS
sheet in mind rather than a reader/developer.
Its not uncommon to see HTML markup like this in the source code of modern websites:
<div class="row">
<div class="col-md-4">
Name:
</div>
<div class="col-md-4">
John
</div>
<div class="col-md-4">
Smith
</div>
</div>
<div class="row">
<div class="col-md-12">
<p>
"I enjoy writing code in my spare time."
</p>
</div>
</div>
Bootstraps CSS files know exactly what to do with that. Two rows, one split into thirds and the other
full width. As developers who are familiar with Bootstrap, thats easy enough for us to figure out, but
what if youd never used the framework before? What is this snippet of HTML for? What does the
information pertain to? The markup isnt revealing anything practical.
Semantic markup is code that describes its content rather than its appearance. We could write the code
<div class="author-name">
<label class="author-nameLabel">
Name:
</label>
<span class="author-nameFirst">
John
</span>
<span class="author-nameLast">
Smith
</span>
</div>
<div class="author-bio">
<p>
"I enjoy writing code in my spare time."
</p>
</div>
Its not all that different but it immediately tells us what each element is for and how each one might
relate to other elements. What weve lost is the knowledge of how this will be presented visually. But
thats not the purpose of HTML after all.
your markup? Well, we can leverage the power of Sasss @extend functionality to solve this problem.
From Sasss documentation:
@extend works by inserting the extending selector anywhere in the stylesheet that
the extended selector appears.
This means we can use our semantic selectors and extend Bootstraps selectors to get all of its goodness.
Heres how:
/* Author Bio and Author Name are just Bootstrap .row elements */
.author-bio,
.author-name {
@extend .row;
}
/* Author nameLabel, nameFirst and nameLast need
to be a third of their container's width */
.author-nameLabel,
.author-nameFirst,
.author-nameLast {
@extend .col-md-4;
}
/* The paragraph inside the author's bio should be full width */
.author-bio p {
@extend .col-md-12;
}
Through the magic of @extend, our selectors are slotted in to the compiled stylesheets alongside the
Bootstrap selectors they extend. As youll see by examining the compiled code, our selectors have all the
For example, among other things, you should see this in the compiled CSS:
* one of the compiled rule sets */
.col-md-4, .author-nameLabel,
.author-nameFirst,
.author-nameLast {
width: 33.3333333333%;
}
Reusability
Another great thing about this method is that it creates readable and reusable components. For example,
you dont have to rebuild the author component out of rows and columns each time you need to use it.
Instead, you have sensible names for each part of the component, making it easy to construct. You can
also rely on Bootstrap to make sure its presented uniformly across your site.
Portability
While Boostrap is one of the best frameworks available, the time may come when you want to move
your site to a different framework or even write your own. With the above outlined method you can do
so easily because your markup is cleanly decoupled from your CSS.
github page.
Sass isnt the only thing at play here. If you truly want next-level semantics in your HTML and CSS, I
recommend adopting a naming convention such as BEM or SMACSS to keep your selectors standardized and easy to remember.
something presentable at the loss of quality markup. With Sasss @extend directive, youre free to write
markup that speaks clearly both to its contents and to the developers reading it.
After the much awaited news, as you can probably guess, I downloaded the source files for Bootstrap 4
and spent some time going back and forth between reading the docs and digging into the code to find
out more.
I expect the alpha release of Bootstrap 4 will undergo a number of changes in the coming weeks, even
months. The curious among you, can keep an eye on the issues section of the projects GitHub repository.
However, the features Im going to list here are more like broad coding principles and practices that
keep improving on each new release of the framework. Thats why I think its likely theyre here to stay.
crucial role of being a living document, that is, a tool in sync with the collaborative effort of building the
framework and communicating it to others:
Abstracting and documenting components became part of our process for building
this one tool and Bootstrap in tandem. Mark Otto in 2012
Mark himself is quite a fan of great documentation. His [Code Guide by @mdo](http://codeguide.co/)
is evidence of his approach to high quality documentation as being part and parcel of outstandingly
coded projects.
The documentation for version 4 has been rewritten from scratch using Markdown. Understandably,
given the alpha stage of this version at the time of writing, its still a work in progress.
search form.
}}
include instructions and how-tos covering all areas of the framework, from different ways of
installing Bootstrap to using each component and dealing with browser quirks.
If you take the time, youll soon find a few valuable nuggets scattered throughout various sections of the
docs. For instance, dealing with over-sized SVG images that use the .img-responsive class in IE9-10,
accessibility best practices, enabling the mq4-hover-shim to fix sticky :hover styles on mobile devices,
Finally, if youd like to run the Bootstrap docs locally on your computer, install Jekyll, a great website
building tool, and follow these instructions.
profuse quantity of components. The good news is: Bootstrap 4 has both simplified and further modularized its structure.
To begin with, some components have been eliminated altogether: the Glyphicons icon library is not
bundled with the framework any more; panels, wells, and thumbnails are replaced by the Cards
component. Also, all CSS reset/normalize code and basic styling are now dealt with in a single brand
new module called Reboot.
Further, more than ever before, using Bootstrap now feels like assembling and arranging Lego blocks in
Opt-in Modules
You can quickly control the application of complex CSS features by toggling the value of a Boolean SCSS
variable. Grab your copy of the Bootstrap 4 alpha release source files, open _variables.scss in a
code editor, and find the following snippet (at about line 46):
$enable-flex:
false !default;
$enable-rounded:
true !default;
$enable-shadows:
false !default;
$enable-gradients:
false !default;
$enable-transitions:
false !default;
Toggling the value of one of the above variables from true to false or vice versa, and compiling the
code, will enable or disable the corresponding CSS property in your project.
Lets have a go at turning a traditional Bootstrap grid into a cool Flexbox-powered grid.
Heres the HTML for a regular Bootstrap three-column grid:
<section class="container">
<div class="row">
<article class="col-md-4 col-sm-6">
<header>
<h1>Col 1</h1>
</header>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</article>
<article class="col-md-4 col-sm-6">
<!-- Same code as above -->
</article>
<article class="col-md-4 col-sm-6">
<!-- Same code as above -->
</article>
</div><!-- .row -->
</section><!-- .container -->
Look into the source code using the developer tools of your browser of choice. The CSS rules corresponding to the .row class should look like the image below:
Next, set the $enable-flex variable to true, compile and refresh the browser. Although the browser
display is the same as before, the CSS is different. The .row class turns its element into a flex container
with the flex-wrap property set to wrap. This ensures that child elements exceeding the containers
width wrap to the next row.
Each of these files includes only selected portions of Bootstrap. If you dont need the full-blown
framework in your project, this is a great head-start: just compile one of the light-weight options and
Corresponding cut-down compiled packages will be made available for download from the Bootstrap 4 docs page.
Reusable Components
You can skin and modify components by mixing and matching a few classes. For instance, the brand new
Cards component is a great example of this versatility in action.
Heres all the HTML you need for the simplest instance of this component:
<div class="card">
<div class="card-block">
<p class="card-text">Just some text.</p>
</div>
</div>
This flexible component easily adapts to a variety of content types. Heres an instance that includes an
image, text, links, and a list:
<div class="card">
<img class="card-img-top" src="http://lorempixel.com/290/200/abstract/8" alt="">
<div class="card-block">
<h4 class="card-title">Card title</h4>
<p class="card-text">
The Cards component nicely fits an image on top,
some text, a list, and a couple of links.
100 - Bootstrap: A SitePoint Anthology
</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">Cras justo odio</li>
<li class="list-group-item">Dapibus ac facilisis in</li>
<li class="list-group-item">Vestibulum at eros</li>
</ul>
<div class="card-block">
<a href="#" class="card-link">Card link</a>
<a href="#" class="card-link">Another link<</a>
</div>
</div>
You can also arrange cards in touching equal width and height columns by wrapping them in a
.card-group container:
<div class="card-group">
<div class="card">
<!-- card code here -->
</div>
<div class="card">
<!-- card code here -->
</div>
<div class="card">
<!-- card code here -->
</div>
</div>
Alternatively, you can group Cards having equal width and height columns with margins, using
<div class="card-deck-wrapper">
<div class="card-deck">
<div class="card">
<!-- card code here -->
</div>
<div class="card">
<!-- card code here -->
</div>
<div class="card">
<!-- card code here -->
</div>
</div>
</div>
Another cool thing you can do with Cards is build a Masonry-like layout. Just wrap the cards in a
container with the .card-columns class and leave the rest to Bootstrap.
<div class="card-columns">
<div class="card">
<!-- card code here -->
</div>
</div>
To dive into the details of the Masonry-like Cards layout, as well as exploring further what you can do
with Cards, check out the Cards docs.
Here Ive offered only a few examples of Bootstraps modular architecture. I think these suffice to show
how flexibility and extensibility are built into the framework as a whole, which makes it fun and
convenient to use.
for smaller screens first and progressively add or adjust features as you target larger screens. Version 4
makes further improvements towards adaptive web design by taking the following steps.
earlier version with relative rem and, for media queries, em units. The goal is to have all elements on a
Lets have a look at how Bootstrap sets the global font-size. Start by opening _reboot.scss in a
code editor and find the following snippet (about line 60):
html {
// Sets a specific default `font-size` for user with `rem` type scales.
font-size: $font-size-root;
/* etc... */
}
body {
// Make the `body` use the `font-size-root`
font-size: $font-size-base;
/* etc... */
}
If you dig into _variables.scss, youll see that $font-size-root is set to 16px and
$font-size-base is set to 1rem. This means that dividing any measurement in px by 16, youll come
up with the corresponding rem measurement, e.g., to get the corresponding rem measurement for 40px,
Most importantly, this means its easier to build web pages where all elements proportionally scale up or
down with the screen size without messing up your beautiful design.
This breakpoint is applied using the .col-xl- class and is triggered on screen sizes from 75em upwards.
including myself, obsess over. Its a demanding task and the plethora of screen resolutions available
To help us keep both vertical and horizontal spacing between elements under tight control, Bootstrap 4
resets margin-top to 0 while keeping a consistent margin-bottom value on all elements.
Further, the framework offers an impressive number of utility classes to make it easier for us to adjust
margins and padding at a more granular level across varying screen sizes.
Conclusion
At the dawn of the Bootstrap 4 alpha release, Ive introduced three broad features that in my view make
this front-end framework really stand out:
}} Great documentation
Did you notice I didnt mention Bootstraps move from Less to Sass? Or the rewrite of all JavaScript
plugins in ECMAScript 6?
I consider these to be more like indications of Bootstrap staying current and taking advantage of the
latest tools, rather than features integral to the framework itself.