Twitter Bootstrap Best Practices and Tips by Toptal Developers

Share

This resource contains a collection of Twitter Bootstrap best practices and Twitter Bootstrap tips provided by our Toptal network members.

This resource contains a collection of Bootstrap best practices and Bootstrap tips provided by our Toptal network members. As such, this page will be updated on a regular basis to include additional information and cover emerging Bootstrap techniques. This is a community driven project, so you are encouraged to contribute as well, and we are counting on your feedback.

As with any technology, and especially with frameworks, there’s a difference between knowing Bootstrap and really knowing Bootstrap. By featuring the most up-to-date Bootstrap best practices and tips, we can help you to make that difference, and identify you as a developer that not only understands Bootstrap but is also a master of the Bootstrap framework.

Check out the Toptal resource pages for additional information on Bootstrap common mistakes, a Bootstrap hiring guide, Bootstrap job description and Bootstrap interview questions.

Bootstrap Advantages and Alternatives for Developers

Some developers are very enthusiastic fans of Bootstrap, and they will use Bootstrap wherever they can. Other developers are on the opposite side, and they have their own reasons to avoid Bootstrap all together. Here are some reasons behind both sides of the story, shared by our Toptal developers.

Bootstrap’s main advantages are that it is responsive by design, it maintains wide browser compatibility, it offers consistent design by using re-usable components, and it is very easy to use while being quick to learn. Bootstrap comes bundled with basic HTML and CSS design templates that include many common UI components, which will generate a UI that will handle multiple browsers, devices, and resolutions. It also offers rich extensibility by using JavaScript. It comes with built-in support for jQuery plugins and a programmatic JavaScript API. Not to mention that Bootstrap can be used with any IDE or editor, and any server side technology and language.

One Toptal developer recently had to quickly create an embed system. He decided to use Bootstrap because he didn’t want to break the existing theme of the site by embedding it. What he ended doing is he copied all the Bootstrap SASS files, removed all unnecessary modules, and put a class before calling the import, so it only affects the embed system. After the compile, all worked like a charm. For him, a developer and not a designer, Bootstrap is a blessing because it’s flexible and offers a lot of options, and he can build or adapt the framework as he wants it. It has all the features he needs, and cleaning up unnecessary components requires just a few minutes of work.

On the other side are developers that don’t like Bootstrap at all. One of the reasons is that it was built by Twitter. The problem with big companies is that at some point they just enforce what they think is best and don’t listen to the users. Bootstrap is an open source project, but being backed by a big company can have its ups and downs. The upside is obviously funding, and a core team that is working on the project. The downside is that it’s always shadowed by the investors demands and that it is not so much community driven. Paying clients come first for them, and community comes second.

For developers that are looking for a Bootstrap alternative, Toptal developers recommend Skeleton. Skeleton is a CSS framework, or how they call it, a boilerplate. It is simple and lightweight, with only around 400 lines of CSS code. There is no need to compile the code, because it is written in pure vanilla CSS. It doesn’t include the large number of components like Bootstrap does; it contains only fundamental CSS rules for raw HTML elements and provides a responsive grid. All this means it is lighter, faster, and simpler than Bootstrap. It is also built with mobile first in mind and is open sourced on Github.

Contributors

Franco Risso

Freelance Twitter Bootstrap Developer
Germany

Franco has been working on PHP, MySQL, and JavaScript since the dark days of Internet Explorer 5. He loves REST APIs to separate consumers from providers and TDD to improve code quality. He thrives in Node.js frameworks like Express and React/Redux for the front end. He has read extensively on startups and believes in their potential to bolster economy and social progress. He is a proactive individual, constantly striving to improve his work.

Show More

Get the latest developer updates from Toptal.

Subscription implies consent to our privacy policy

How to support IE8 and other older browsers?

HTML5 introduced new semantic elements and great new features for web developers and designers who want to code readable and semantically meaningful layouts. However, support for HTML5 is still evolving. HTML5 is supported in all modern browsers, but unfortunately some browsers are slow in adding a support for modern standards. The other problem is that some users fail to upgrade their browser of choice, and they are still using old Internet Explorer 9 or older, Safari 4.x (and iPhone 3.x), or Firefox 3.x. They all don’t support HTML5 nor CSS3. Because of this, we need to somehow instruct them how to handle (to them) “unknown” HTML elements.

The first and usual choice is just to use HTML5 shiv. And while this is a valid solution that works, Toptal developers have a few reasons to recommend another framework - Bootstrap.

Bootstrap is designed and built to work at its best in the latest desktop and mobile browsers, but it also supports older browsers. Some components and elements might display different styles, but everything should be fully functional. Support includes Internet Explorer 8 and 9, with usual important note that some CSS3 properties and HTML5 elements are not fully supported by these browsers.

A very basic Bootstrap “Hello world” HTML template example looks like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap Template</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <h1>Hello, world!</h1>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

What is important here is to start HTML with an HTML5 Doctype declaration, so that a browser knows what kind of a document it can expect. The head contains three important <meta> tags that must be declared first, and any additional head tags must be added after them. To get full support for Internet Explorer 8 and other older browsers, we can use a polyfill for CSS3 Media Queries Respond.js, and previously mentioned HTML5 shiv which enables use of HTML5 elements. To make sure that Internet Explorer is not running in compatibility mode, we also need to add proper IE <meta> tag in the HTML head.

The final HTML file in the end should look something like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <title>Bootstrap Template</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <h1>Hello, world!</h1>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

Now, not only does our web application will support old browsers, but in the same time we have a very good set of reasonable CSS defaults to choose from; so we are able to concentrate more on the development work than worrying about design and legacy browsers, and we can use all modern HTML5 and CSS3 goodies safely.

Create a form progress bar using Twitter Bootstrap

Complex web applications usually require a significant amount of data from their users, and forms are one of the primary tools that allow those applications to retrieve and handle data, whether for storage or using it to generate information.

It is an important matter to stimulate and facilitate users to provide this data. If the developers and designers do not do so, users are likely to run away from the forms and avoid using the applications.

There are many tools and techniques that help build easy to use and attractive forms to make sure users are not giving up filling them, such as gamification, splitting forms into smaller and self-contained parts and letting users feel a sense of progress. The latter is pretty significant and useful. If users see how much they advanced and how much is left for them to fill, they are more likely to continue filling the form (or saving current progress to continue later).

Since Bootstrap is a consolidated framework amongst the development community (as they say, “Bootstrap makes front-end web development faster and easier”), let’s see how to build a progress bar that auto increases/decreases as users fill or erase inputs.

The first step is to write the HTML code for the Bootstrap progress bar component:

<p><strong>Progress:</strong></p>
<div id="progress-inputs" class="progress">
    <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
        <span class="sr-only">0% Complete</span>
    </div>
</div>

The code above will produce a result like this:

Bootstrap progress bar

Let’s also write the markup of a small form so we can test our future script:

<form id="input-progress" role="form">
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" id="name" name="name" class="form-control">
    </div>
    <div class="form-group">
        <label for="age">Age</label>
        <input type="text" id="age" name="age" class="form-control">
    </div>
    <div class="form-group">
        <label for="street">Street</label>
        <input type="text" id="street" name="street" class="form-control">
    </div>
    <div class="form-group">
        <label for="city">City</label>
        <input type="text" id="city" name="city" class="form-control">
    </div>
    <div class="form-group">
        <label for="state">State</label>
        <select id="state" name="state" class="form-control">
            <option value="">- Select -</option>
            <option value="ST1">First State</option>
            <option value="ST2">Second State</option>
            <option value="ST3">Third State</option>
        </select>
    </div>
    <div class="form-group">
        <button type="button" class="btn btn-success">SEND</button>
    </div>
</form>

Our little form will look like this:

Bootstrap form

Now let’s do the fun part - write a small JavaScript code to make the progress bar react to the inputs filling and select choosing. We are going to update the progress bar when one of the following events occur:

  1. Any form element (inputs and select) are focused out. This is because we don’t want to recalculate the progress after each keypress. We just need to update the progress bar once the user finishes editing an element and navigates to another one.
  2. The SEND button is clicked. We want to recalculate the progress when this button is hit since we can do another action (like showing a feedback message, for example) in some cases. Example: showing a congratulations message if everything is filled.

To make the progress bar work, we just need the following piece of JavaScript code:

<script type="text/javascript">
    $(document).ready(function() {
        function updateInputProgress() {
            var filledFields = 0;
            $('#input-progress').find('input, select').each(function() {
                if ($(this).val() != '') {
                    filledFields++;
                }
            });

            var percent = Math.ceil(100 * filledFields / totalFields);
            $('#progress-inputs .progress-bar')
                    .attr('aria-valuenow', percent)
                    .width(percent + '%')
                    .find('.sr-only').html(percent + '% Complete');

            return percent;
        }

        // Input progress.
        var totalFields = $('#input-progress').find('input, select').length;
        $('#input-progress').find('input, select').blur(function() {
            updateInputProgress();
        });
        $('#input-progress .btn-success').click(function() {
            var percent = updateInputProgress();
            if (percent == 100) {
                alert('Finished inputs successfully!');
            }
        });
    });
</script>

Note that the updateInputProgress() function is called when any input or select element is blurred and also when the button is clicked, like explained above. If your form has other elements (like text areas) we can just increase the list of elements that listen to the blur event, and also increase the list of elements used to calculate the progress on $('#input-progress').find('input, select').each(function() {.

The examples can be downloaded, or you can see them visualized. There are two examples: updating the progress bar for each input and updating the progress bar when an entire fieldset is filled.

Contributors

Flavio Escobar

Freelance Twitter Bootstrap Developer
Brazil

Flavio is a top developer and an aspiring entrepreneur. He has extensive experience and skills with web and game development and is also proficient with mobile applications. He is a master of PHP, JavaScript, and WordPress.

Show More

Improve User Experience by Using a Spinner with jQuery Global Ajax Calls.

Part of every design process is taking care of the user experience (UX). Small things and catchy details make a significant difference between good UX and an excellent UX.

Let’s consider a situation when you are on a web page and need to fetch some additional data in the background. Modern web applications are using Ajax calls, instead of doing a submit and reloading a whole page. An Ajax call is an asynchronous call where the UI of the web page is not changing, and the user is often not aware that some process is happening behind the scene. An Ajax call can finish very fast, but in case of bad network connections or heavy load on the server from where the data is fetched, it can last a few seconds, or even a lot more. Toptal developers are always sweating over the details to get the best experience for their clients, and here they are sharing how to use the help of jQuery, little spinner graphics, and a few lines of code to improve your UX.

When doing an Ajax call, you can show a little spinner graphics to notify the user that something is going on in the background. This spinner can be shown and hidden with jQuery global calls.

We will be utilizing native jQuery functions ajaxStart and ajaxStop. The main catch here is to define them only once, and call them only when Ajax calls start and finish, so we do not have to duplicate our logic elsewhere in the code.

For example, we can define one div in the body element, with id="spinner". Inside the div element we positioned a nice looking FontAwesome spinner. You of course can use any GIF animation, or similar object that you like. With the JavaScript code we are only altering it to be shown or hidden when start and finish events are raised.

Just do not forget to hide spinner initially on the page. Once that’s defined, you can focus on the application logic and doing actual Ajax calls.

The following few lines of code should make your UX much more intuitive and your users much happier:

/* make toggle nav on left */
$('.list-group a').click(function(){ 
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
});
/* show spinner */
$( document ).ajaxStart(function() {
    $('#spinner').removeClass('hidden');
});
/* hide spinner */
$( document ).ajaxStop(function() {
    $('#spinner').addClass('hidden');
});

Here is the example code in place, enhanced with a little help from Twitter Bootstrap:

Contributors

Kresimir Pendic

Owner and web developer (MK dizajn)

Kresimir has over five years of experience developing custom modules (plugins) and themes for WordPress CMS, Magento platform, and front-end UI. He has been known to fiddle with custom JavaScript and develop for strictly front-end and mobile grounds. His communication is very good, and his level of dedication is impressive.

Submit a tip

Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.

* All fields are required

Toptal Connects the Top 3% of Freelance Talent All Over The World.

Join the Toptal community.