Rapid web development with Bootstrap

Get your website designs off the ground with Twitter Bootstrap

Learn how to use Bootstrap to kickstart websites and web applications, including mobile-friendly ones. Bootstrap, which is based on the LESS project, was developed by Twitter's internal engineers to provide a consistent framework for web application UIs.

Uche Ogbuji, Partner, Zepheira, LLC

Uche OgbujiUche Ogbuji is a partner at Zepheira, where he oversees the creation of sophisticated web catalogues and other richly contextual databases. He has a long history of pioneering in advanced web technologies such as XML, Semantic web, web services, and open source projects such as Akara, a platform for web data applications. He is a computer engineer and writer born in Nigeria, living and working near Boulder, Colorado, USA. You can find more about Mr. Ogbuji at his blog: Copia.



06 August 2013

Also available in Chinese Russian Japanese

When simple isn't

The concept of the World Wide Web is simple. A standard transport protocol (HTTP) gets information from the server to the client, and a standard declarative language (HTML) expresses the content so that browsers can render it visually. In practice, though, the web's success doomed this simplicity, and web development hasn't been as easy as it should be. Competition for features among browsers led to complication of the standards and to variations in browser behavior. Extraordinary skill and experience was then required to ensure that a page looked and worked similarly in different browsers and on different platforms. (More-benign complications, such as accessibility for the visually impaired and worldwide support for languages and scripts, also resulted.) Web developers and designers are managing these matters better now, but the basic quirks in dealing with cross-browser HTML remain.

Browser developers are finally converging in their support for standards such as HTML5, Cascading Style Sheets Level 2 (CSS2), and CSS3. These standards reduce the unreasonable variations in browser behavior that have plagued developers and designers since the web's inception. To paper over remaining problems and to accommodate legacy browsers, some developers have produced web page frameworks. Such tools make it feasible for a mere mortal to develop sites that should work for most users.

One of the most popular modern web page frameworks comes from an unexpected source. Developers at Twitter were tired of wrestling with the many disparate components that they used for web page development. They created a single framework that provides the most common elements of page design while allowing reasonable flexibility. They shared this toolkit with the world in the form of Bootstrap, which is an open source project.

Bootstrap is based on the LESS project, which enhances the CSS language. Bootstrap also includes basic CSS elements for typography, forms, buttons, tables, grids, navigation, alerts, and much more. Bootstrap's main purpose is to help web developers accelerate their projects. It's now the most popular project in the GitHub software repository. Individuals, small teams, and even large organizations are all using Bootstrap.

This article shows you how to use Bootstrap to kickstart your websites and applications, including mobile-friendly ones. The article reflects a developer's point of view rather than a designer's. To benefit from the article and from Bootstrap, you need working knowledge of HTML and CSS. Basic knowledge of the LESS project, which I cover in "Do more in CSS with LESS," can help you to understand this article's main code example.

Getting started

Download the compiled Bootstrap package (see Resources). I use version 2.3.2 in this article. The download contains the CSS that's at the heart of Bootstrap, along with useful images and JavaScript. You supply the HTML for your web page, as I outline in this article. (See Download to get this article's sample code.) The Bootstrap documentation does include sample HTML for the many design options that the framework supports. But the Bootstrap documentation pages — although they themselves exemplify Bootstrap's flexibility — don't adequately explain the basic design principles that are at play.

Responsive web design

Devices for viewing web pages can range from small mobile handsets to displays that are larger than the usual desktop computer form factor. In responsive design, you build flexibility into web pages from the start so they are viewable in all devices. At the heart of responsive design are CSS3 media queries, a standard way to invoke CSS rules according to the nature and, especially, size of the user's display.

For the kinds of projects that a typical developer initiates, I recommend starting with a fixed layout with responsive features enabled. The fixed layout is easier to organize, and the responsive features support a sound habit of thinking about how your site works on mobile devices from the start. If your project does go on to production and you're working with designers, the designers should be able to adapt your files to any other model that's more suitable.

HTML for Bootstrap

Listing 1 is a useful skeleton HTML file for using Bootstrap with a fixed layout and responsive features:

Listing 1. Basic skeleton HTML file for Bootstrap projects (listing1.html)
<!doctype html>
<html>
  <head>
    <title>Bootstrap 101 Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  </head>
  <body>
    <h1>Hello world!</h1>
    <div class="container">
    ... <!-- The main HTML will go here -->
    </div>
    <script src="http://code.jquery.com/jquery.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

Minified versions

In the Bootstrap download, notice that two versions of each CSS and JavaScript file are available (for example, bootstrap.js and bootstrap.min.js). The first form is a regular file, and the second form is compressed, or "minified." Use the minified versions, as I do in this article, for the most efficient page loading.

The DOCTYPE declaration at the start of listing1.html marks it as an HTML5 file. The meta tag that's within the head element controls mobile, small-screen layouts. (For convenience, I'll refer to it as the meta/viewport tag.) By default, most mobile devices scale down web pages so that they fit on the screen, as they do in a desktop browser window. This is why the text and images on many websites look tiny in your mobile phone's browser. The initial-scale=1.0 part of the meta/viewport declaration disables this behavior, telling the device to keep the page's original scale. The declaration indicates that the web designer (Bootstrap, in this case) has already done the work to implement responsive design for smaller screens, so the default, brute-force approach is unnecessary.

Later on in Listing 1's head tag are links to the Bootstrap CSS. At the end of the file, jQuery and the Bootstrap utility JavaScript load. These scripts run at the end for optimal performance.

Setting up the code

You can choose among many approaches to setting up HTML and other code when you use Bootstrap (or any set of web support files). I recommend that you create a folder for your own project and then copy the Bootstrap files, with their complete folder structure intact, to your project folder. Put your own HTML files at the top level, and put your own CSS, JavaScript, and image files in the corresponding Bootstrap subfolders (which are named css, js, and img, respectively). The overall structure then looks like this:

.
|—— index.html
|—— [Also any other site HTML]
|—— css
|   |—— bootstrap.min.css
|   |—— bootstrap-responsive.min.css
|   |—— [Also nonminimized Bootstrap files plus site-specific CSS]
|—— js
|   |—— bootstrap.min.js
|   |—— [Also nonminimized Bootstrap files plus site-specific JavaScript]
|—— img
    |—— [The PNGs that come with Bootstrap plus site-specific images]

CSS device adaptation

The meta/viewport tag is the current convention for adapting a page to a devices' viewable browser space. The World Wide Web Consortium (W3C) is preparing a replacement mechanism, in the form of a new sort of CSS rule (see Resources). The equivalent CSS to the meta/viewport declaration in Listing 1 is:

@viewport {
  width: extend-to-zoom 100%;
  zoom: 1.0;
}

For now, you can include this code in your CSS and keep the meta/viewport tag in the HTML. You can remove the meta/viewport declaration when the CSS form is broadly supported.


The grid system

The main container div in Listing 1 signals use of Bootstrap's fixed layout. The HTML that you put into this container integrates into Bootstrap's grid system.

If you think of most web pages that you've seen, you realize that they are divided into a series of blocks. A block that goes across the top of the page might hold a logo. Perhaps the navigation is in a block on the left or right side, and an index of content fits in there too. Perhaps yet another block contains a footer. The main content itself might be divided into panels or blocks. In the past, web designers set up all of these blocks by hand by using the CSS box model.

A grid system is a way to abstract away a box arrangement such as the one I've just described into rows and columns. Bootstrap provides a core of CSS for such a grid. You can place content in any layout of boxes by nesting div elements through the use of special classes.

Figure 1 shows a useful template, originally developed by Aaron K. White, for visualizing Bootstrap's grid system and planning how to arrange your content (see Resources). I've modified it only to make the text easier to read in this article.

Figure 1. Aaron K. White's Bootstrap grid system template
Browser screenshot

The Bootstrap grid system has a maximum of 12 blocks per row, with gutters between the blocks to provide spacing. You can have an unlimited number of rows, each with any height you like. Each block is 70 pixels wide, and the gutters are 30 pixels wide. Bootstrap also sets up a left margin of 30 pixels for the page body. The grid system is designed to take care of basic arrangement and spacing for you so that, ideally, you concern yourself only with what to put into the grid.

Filling out the HTML template

In "Do more in CSS with LESS," I use an example of responsive design (based on developerWorks blogger Bob Leah's example) to demonstrate how the LESS tool enhances CSS syntax. Bootstrap is a great tool for simplifying the many concerns from that code. Listing 2 is the HTML from that article (responsive.html in the code download), rewritten (as listing2.html) to work in Bootstrap's fixed layout grid system, and supplemented with Bootstrap's responsive features:

Listing 2. Example HTML file for Bootstrap (listing2.html)
<!doctype html>
<html lang="en-US">
  <head>
    <title>Responsive Bootstrap page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      <h1>Hello world!</h1>
      <div class="row">

        <div id="banner" class="span12">
          <!-- Photo by Jake Sutton
          http://www.flickr.com/photos/44124405407@N01/510899838 -->
          <img src="img/sky-slim.jpg">
        </div>  
      </div>
      <div class="row">
        <div id="main-content" class="span8">
          <p>Humpts dumptus in muro sedet
          </p>
          <p>Veni vidi vici
          </p>
          <p>Alea iacta est
          </p>
          <hr>
        </div>
        <div class="span4">
          <div class="widget-title">One</div>
          <div class="widget-text">
            The quick brown fox jumps...
          </div>
          <div class="widget-content">
            <div class="widget-title">Two</div>
            <div class="widget-text">
              Over the lazy dog...
            </div>
          </div>  
          <div class="widget-content">
            <div class="widget-title">Three</div>
            <div class="widget-text">
              To get to the other side
            </div>
          </div>
        </div>  
      </div>
      <div class="row">
        <div id="footer" class="span12">
          &copy; Nobody! This document is placed in the public domain.
        </div>  
      </div>
    </div>
    <script src="http://code.jquery.com/jquery.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

In Listing 2, Bootstrap eliminates much of what I had to work out manually in the older responsive-design code. I no longer need specialized CSS for manipulating and scaling box sizes, because the page uses Bootstrap's grid system. No CSS for carefully arranging the visual spacing is necessary, because the Bootstrap grid sets good defaults between blocks. And I don't need any CSS to make the media queries and set up the response in the design parameters, because Bootstrap's responsive features take care of those tasks.

You can see the nesting of the div tags in Listing 2. The nested divs use the Bootstrap grid classes. The div with the container class is the wrapper for the entire fixed grid layout. Each div with a row class defines a row of boxes in the grid. The divs with a span4 class define a block that is 4 boxes across. The divs with a span12 class define a block that is 12 boxes across — the full width of the page. Bootstrap has a spanN class for spanning any number N of boxes from 1 to 12.

Figure 2 shows how the resulting page looks in a mobile browser (Google Chrome on my Samsung Galaxy S3 running Android 4.1.1):

Figure 2. Browser output from Listing 2
Browser screenshot

Site-specific CSS

The main elements of the page that's shown in Figure 2 are in the right arrangement. But the page lacks style elements to make it more appealing to the eye, so I'll add some CSS (main.css in the sample code) for this purpose. The Bootstrap CSS itself is written in LESS, and in general I highly recommend using LESS rather than plain CSS. But for this simple example, the plain CSS in Listing 3 will suffice:

Listing 3. CSS for adding basic design to the example HTML (main.css)
.widget-content {
  margin: 10px;
  padding: 1px;
  background-color: #DDDDDD;
}    

.widget-title {
  font-weight: bold;
  padding: 10px;
  background-color: #EEEEEE;
}    

.widget-text {
  padding: 10px;
  background-color: #FCFCFC;
}    


#footer {
  text-align: center;
  font-size: small;
}

Of course the HTML in Listing 2 now needs an added link for the site-specific CSS in Listing 3. In the sample code the updated HTML that includes a link to main.css is in the main.html file. Figure 3 shows the resulting page, which main.css makes a bit more presentable:

Figure 3. Browser output from main.html
Browser screenshot

Wrap-up

For me and the many others whose strengths are in code and data rather than in visual and other sensory design, Bootstrap is a valuable tool. I can focus on the basic code and data for a web project and get it into rudimentary shape, then work with designers to polish the page. Bootstrap helps with some particularly tricky areas such as design for mobile devices and other small-screen settings. It also comes with a library of buttons, navigation styles, and other reusable tools. Above all, Bootstrap includes a lot of code to reduce many of the vexing variations among web browsers and platforms.

So many projects use Bootstrap that many people can now instantly recognize a Bootstrap-based site. This recognition can sometimes create an impression of unoriginality. A good designer can not only give a Bootstrap-generated site its own distinct character, but also ensure that the site's basic and responsive elements are well-specialized to its content and uses. But few projects get off the ground with such considerations in mind. Bootstrap is especially helpful for quickly turning glimmers of ideas into web projects.


Download

DescriptionNameSize
Sample codewa-bootstrapcode.zip41KB

Resources

Learn

Get products and technologies

  • Bootstrap: Dive into Bootstrap and get the code at the official project page.
  • Bootstrap Illustrator Template: Draft the grid of your Bootstrap designs with help from Aaron K. White's template.
  • Evaluate IBM products in the way that suits you best: Download a product trial, try a product online, use a product in a cloud environment, or spend a few hours in the SOA Sandbox learning how to implement Service Oriented Architecture efficiently.

Discuss

  • Get involved in the developerWorks community. Connect with other developerWorks users while exploring the developer-driven blogs, forums, groups, and wikis.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, Open source, Mobile development
ArticleID=939386
ArticleTitle=Rapid web development with Bootstrap
publish-date=08062013