facebook google plus twitter
Webucator's Free Developing Mobile Websites Tutorial

Lesson: The Bootstrap Framework

Welcome to our free Developing Mobile Websites tutorial. This tutorial is based on Webucator's Responsive Web Design Training course.

In this lesson, you will learn how to use Bootstrap, a powerful grid-based layout for building responsive websites.

Lesson Goals

  • Learn how to use the Bootstrap framework to quickly and easily build responsive websites.
  • Learn how to use Bootstrap's grid, components, and other features.

Bootstrap: A Responsive Framework

Wouldn't it be nice if we could avoid the specifics of all of those grid layout percentage widths and media queries and concentrate on higher level layout considerations? If typography, buttons, forms, and other UI elements started from some good-looking CSS styles but were easy to modify? With the advent of responsive design has come the welcome arrival of frameworks - self-consistent HTML/CSS/JavaScript systems for quickly and easily building responsive sites.

Originally built by Twitter and open-sourced in 2011, Bootstrap is downloadable for free, either from the http://getbootstrap.com/ website or from the Bootstrap GitHub page. Bootstrap takes away a fair amount of the low-level implementation details when building a responsive site: flexible grids, media queries, flexible images, and other familiar aspects of responsive sites are baked in. You can (and will) exert fine-level control over CSS, JavaScript, and other aspects of sites you build with Bootstrap.

Downloading Bootstrap

To use Bootstrap, download the most recent version from getbootstrap.com/getting-started/#download:

download Bootstrap

We've done so already - the example files (demos, exercises, and solutions) in the TheBootstrapFramework directory all reference the 3.3.2 version we downloaded from the Bootstrap website. We use the "Bootstrap" (compiled and minified) version here; advanced users may want to check out the "Source code" version or the "Sass" (a CSS precompiler) versions.

Bootstrap's Grid

Perhaps the most useful resource offered by the Bootstrap framework is the grid: including a series of markup tags with appropriate classes gives us the ability to craft layouts that scale appropriately for different viewport widths. We can create one design for phones, another for tablets, and yet another for desktops or large desktops. Nesting grids within grids allows us to create arbitrarily complex layouts.

By default, Bootstrap works on a 12-column system. A three-column layout targeting desktop-width viewports would have three elements with a width of "4", since 4 + 4 + 4 = 12; on smaller screens - an iPhone, say, the layout would collapse, with the three columns stacked vertically. A two-column layout with one large-width and one small-width column might have elements of "8" and "4" (since 8 + 4 = 12); a user visiting the page from a desktop browser would see one wider left column and one narrower right column, while smartphone visitors would see two equal-width elements, one below the other.

The key to the grid is a series of elements marked up with CSS classes as follows:

  • The outermost element (a <div> tag, say, or a <header> or <article> tag) has class .container (for a fixed-width layout) or .container-fluid (for a full-width layout);
  • Inside a container, elements have class .row to define a row;
  • Inside a row, column elements have classes denoting both the target viewport width and the width of the column, based on the 12-column system:
    • xs targets phones, with viewports less than 768px;
    • sm targets tablets, with viewports greater than 768px;
    • md targets desktops, with viewports greater than 992px;
    • lg targets large desktops, with viewports greater than 1200px.

    Each column class is of the form col-md-6, where the last number indicates the column's width; here, a "6" sets the column at half the container's width for desktop-sized viewports or larger.

    A simple Bootstrap grid might look like this:

    <div class="container">
    	<div class="row">
    		<div class="col-md-6"> col of width 6 </div>
    		<div class="col-md-3"> col of width 3 </div>
    		<div class="col-md-3"> col of width 3 </div>
    	</div>
    </div>

    This code would look like this on a viewport - a desktop browser, for example - sized larger than 992 pixels:

    Code Appearance on Viewport Larger Than 992 Pixels

    and like this on a viewport - a tablet or smartphone, say - sized smaller than 992 pixels:

    Code Appearance on Viewport Smaller Than 992 Pixels

    The background and border color of the column elements (the three <div>s) is a product of CSS styling specific to this example, rather than something that Bootstrap itself imposes. While the Bootstrap framework does include some basic styling, we can - and usually do - style our Bootstrap-enabled pages in a custom manner.

    Bootstrap also offers us visibility classes: applying these classes defines whether the element to which it is applied will show (or not) for a given viewport width. For instance, an element - an image, say, or an <h3> header - with class="visible-xs-block" will show for phones (viewports smaller than 768 pixels) but not for any wider viewports. Conversely, an element with class="hidden-xs" will not show on phones but will show on any device with viewport wider than 768 pixels. Here's a breakdown of the visibility classes:

    Extra small devices Phones (<768px) Small devices Tablets (768px) Medium devices Desktops (992px) Large devices Desktops (1200px)
    .visible-xs-block Visible Hidden Hidden Hidden
    .visible-sm-block Hidden Visible Hidden Hidden
    .visible-md-block Hidden Hidden Visible Hidden
    .visible-lg-block Hidden Hidden Hidden Visible
    .hidden-xs Hidden Visible Visible Visible
    .hidden-sm Visible Hidden Visible Visible
    .hidden-md Visible Visible Hidden Visible
    .hidden-lg Visible Visible Visible Hidden

    You can also use class="visible-xs-inline" and class="visible-xs-inline-block" (for xs, sm, md, or lg) to display elements in inline or inline-block fashion, respectively, instead of class="visible-xs-block".

    Bootstrap also offers a class by which you can render images responsive: in <img src="sample.jpg" class="img-responsive" alt="sample image">, the img-responsive class applies the style rules max-width: 100% and height: auto so that the image scales with its parent element.

    You can find more details and documentation on the Bootstrap grid and utility classes at http://getbootstrap.com/css/.

Bootstrap Components

In addition to the responsive grid, Bootstrap offers a wide range of pre-built user-interface elements: icons, navigation elements, buttons, and other components rendered via Bootstrap's CSS and, for some elements, JavaScript.

For instance, we might use Bootstrap's "pagination" component to present a set of page links for a blog, allowing users to access the next page of blog posts, page 2 of blog posts, etc.:

Page Links

The code for the example above looks as follows:

<nav>
	<ul class="pagination">
		<li>
			<a href="#" aria-label="Previous">
				<span aria-hidden="true">&laquo;</span>
			</a>
		</li>
		<li><a href="#">1</a></li>
		<li><a href="#">2</a></li>
		<li><a href="#">3</a></li>
		<li><a href="#">4</a></li>
		<li><a href="#">5</a></li>
		<li>
			<a href="#" aria-label="Next">
				<span aria-hidden="true">&raquo;</span>
			</a>
		</li>
	</ul>
</nav>

As with all Bootstrap components, the key here is to use the correct markup, class names, and attributes - in this case, an unordered list with class pagination.

Another useful component is "pills", a navigation element presenting a set of buttons. Here is an example of pills set to justify (span the width of the screen) on larger viewports:

Pills Element

and to stack on smaller viewports like phones:

Stacked Pills Element

And here's the code:

<ul class="nav nav-pills nav-justified">
	<li role="presentation" class="active"><a href="#">Link 1</a></li>
	<li role="presentation"><a href="#">Link 2</a></li>
	<li role="presentation"><a href="#">Link 3</a></li>
</ul>

You can find examples and code for all available components on the Bootstrap website.

A First Example

Open TheBootstrapFramework/Demos/index.html both in a browser and in a file editor to check out the code. Notice the difference between viewing the page from a desktop browser:

Bootstrap - desktop

and viewing the page from a phone, or with a desktop browser at a narrow width:

Bootstrap - phone

In general, elements that are horizontal (positioned side-by-side) on the desktop view are vertical (stacked) in the mobile view. Be sure to investigate how the layout changes as you drag the width of your browser wider and narrower, or view the page from a tablet or mobile device. Let's review the code.

Code Sample:

TheBootstrapFramework/Demos/index.html
<!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">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="favicon.ico">

    <title>Bootstrap Examples</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="css/demo.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[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]-->
  </head>

  <body>
    <div class="container">

      <div class="page-header">
        <h1>Bootstrap Example</h1>
        <p class="lead">Basic grid layouts and select Bootstrap component elements.</p>
      </div>

      <h3>Three equal columns</h3>
      <p>Get three equal-width columns <strong>starting at desktops and scaling to large desktops</strong>. On mobile devices, tablets and below, the columns will automatically stack.</p>
      <div class="row">
        <div class="col-md-4">.col-md-4</div>
        <div class="col-md-4">.col-md-4</div>
        <div class="col-md-4">.col-md-4</div>
      </div>

      <h3>Three unequal columns</h3>
      <p>Get three columns <strong>starting at desktops and scaling to large desktops</strong> of various widths. Remember, grid columns should add up to twelve for a single horizontal block. More than that, and columns start stacking no matter the viewport.</p>
      <div class="row">
        <div class="col-md-3">.col-md-3</div>
        <div class="col-md-6">.col-md-6</div>
        <div class="col-md-3">.col-md-3</div>
      </div>

      <h3>Two columns</h3>
      <p>Get two columns <strong>starting at desktops and scaling to large desktops</strong>.</p>
      <div class="row">
        <div class="col-md-8">.col-md-8</div>
        <div class="col-md-4">.col-md-4</div>
      </div>

      <hr>

      <h3>Two columns with offset</h3>
      <p>Two columns with the first column offset by 4.</p>
      <div class="row">
        <div class="col-md-4 col-md-offset-4">.col-md-4</div>
        <div class="col-md-4">.col-md-4</div>
      </div>

      <hr>

      <h3>Nav: Pills</h3>
      <p>Pill navigation, justified to fill the screen on desktops, stacking on mobile.</p>
      <ul class="nav nav-pills nav-justified">
        <li role="presentation" class="active"><a href="#">Link 1</a></li>
        <li role="presentation"><a href="#">Link 2</a></li>
        <li role="presentation"><a href="#">Link 3</a></li>
      </ul>

      <hr>

    </div> <!-- /container -->
  <!-- Bootstrap core JavaScript
  ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
  <script src="js/ie10-viewport-bug-workaround.js"></script>
  </body>
</html>

The <head> of index.html file includes a viewport tag and a link to the css/bootstrap.min.css we downloaded from Bootstrap; note that this CSS file is minified (stripped of whitespace, making for a smaller file) to improve performance with a quicker download.

We also link to a custom CSS file - css/demo.css - that we wrote ourselves. This file is not part of Bootstrap; rather, we added a few lines of CSS to add background color and borders to grid elements, to make it easier to see what's going on.

A conditional statement (<!--[if lt IE 9]) targets older Internet Explorer browsers, including two JavaScript files to improve those older browsers' handling of HTML5 tags.

Near the bottom of the page we include three JavaScript files via <script> tags: a link to jQuery (in this case via a content deliver network, or CDN); a link to Bootstrap's core JavaScript file, bootstrap.min.js; and a link to a Bootstrap JavaScript file (ie10-viewport-bug-workaround.js) that fixes an Internet Explorer bug. This last file (ie10-viewport-bug-workaround.js) doesn't download with the core Bootstrap files; we downloaded it directly from the Bootstrap GitHub site, and recommend including it in production projects to address a known issue with some Windows browsers and Bootstrap.

Inside the <body> of our example file, we present four examples of using the grid and one example of using a component. Note that the outermost element is a <div> tag with class container: this gives us the proper alignment and padding for the contained elements.

The first grid example - three equal columns - starts on line 36: a <div> of class row contains three <div>s each of class col-md-4. For desktop-width (or larger) viewports, these three <div>s display as equal-width, side-by-side elements; each takes up one third of the width of the container. For smaller viewports - an Android or iPhone, say, or a desktop browser dragged narrower - these elements appear stacked vertically.

In the second grid example (starting on line 44), on a desktop-or-larger viewport, we see three unequal columns, with the middle element taking up 50% of the allotted space and the two elements on either side each taking up 25% of the space. Note that the middle <div> element has a class of col-md-6 and the first and last <div>s have class col-md-3. As Bootstrap's grid works from a 12-column system, the "6" class gives that <div> half of the width, and the "3" class gives those two <div>s one quarter of the width. Note that, for smaller viewports, the elements again stack vertically, with each element having equal (100%) width.

The third grid example, starting on line 52, shows two columns: the first spans two thirds of the width (because of the col-md-8 class, "8" being two thirds of "12") and the second spans one third of the width (because of the col-md-4 class). Again, on smaller viewports, the elements stack vertically.

The fourth grid example, which starts on line 61, shows the use of an offset: we have two <div> elements, each with class col-md-4, but the first <div> also gets a class of col-md-offset-4. This offset class pushes the <div> right by the amount indicated (in this case, "4"), so that the two elements each span one third of the width, with the first one pushed right by one third. Notice that the offset doesn't apply for smaller viewports: this fourth example, when viewed on a narrower browser or on a tablet or mobile device, presents the two <div>s stacked vertically.

Finally, on line 70, we show an example of the "pills" navigation element we discussed above: three buttons span the width of the allotted space on larger viewports, while smaller-sized viewports see the three buttons stacked vertically.

A Bootstrap Layout for Jazz Calendar

Let's use Bootstrap to render a new layout for the Jazz Calendar site: we'll use a large background image and slightly-off-to-the-right main content on desktops, and a more straightforward design on phones. Open up TheBootstrapFramework/Demos/jazzcal.html from a browser (and, if possible, from a phone or emulator) and also open the code with an editor to review. Here's the page on a desktop browser:

Bootstrap layout for Jazz Calendar - desktop

On a tablet:

Bootstrap layout for Jazz Calendar - tablet

And on a mobile device:

Bootstrap layout for Jazz Calendar - phone

Notice how the layout changes: we use an offset to position the layout off to the right on wider viewports, lose the offset (but keep the large background image) on tablets, and lose the background image and stack elements vertically on phones. Let's review the code.

Code Sample:

TheBootstrapFramework/Demos/jazzcal.html

Code Explanation:

As with our first example above, we include the needed CSS and JavaScript files: bootstrap.min.css (referenced in the <head>) and bootstrap.min.js (referenced just before the closing </body> tag, at the bottom of the file) are what make Bootstrap work for our page.

We also include, on line 17, a custom CSS file, jazzcal.css, in which we write our own CSS, specific to the page.

The full-page background image of the saxophone player doesn't come from Bootstrap; rather, it comes from our custom CSS file. jazzcal.css includes the following code:

@media(min-width:768px){
	html {
		background: url('../images/bg_sax.jpg') no-repeat center center fixed; 
		-webkit-background-size: cover;
		-moz-background-size: cover;
		-o-background-size: cover;
		background-size: cover;
	}
}

We use a media query to display the background image for viewports of width greater than 768 pixels; narrower viewports don't get the background image.

We also set the font (Georgia) for text on the page, set color for links and some other elements, add some borders, and override the default Bootstrap pills element with some custom colors and borders.

In jazzcal.html, we use Bootstrap grid classes to achieve our desired layout. The <header> (the dark blue element at top), <article> (the main content area), and <footer> (containing the pills navigation) are all classed with container and each contains a <div> of class row.

Inside of each .row element in the <header>, <article>, and <footer>, the content is wrapped in a tag: <div class="col-md-6 col-md-offset-5">. The col-md-6 class sets the element to display, on desktop-sized or larger viewports, as half of its container's width; the col-md-offset-5 class offset - pushes right - the element by 5/12s of the available width. Note that the sum total of the offset and the width don't add up to 12 - we left some space (one twelfth) at the right, for visual effect.

Notice that Bootstrap handles the smaller (tablet- and phone-sized) viewport responsiveness for us: the framework's under-the-hood media queries, tied to the classes we applied, render the layout appropriately for various viewport widths.

We use the visibilty classes to render some elements visible or hidden for specific viewport widths: the <h3 id="tagline" class="hidden-xs">Your local source for local live jazz.</h3> element - because it bears the class hidden-xs in the header - shows for any viewport wider than 768 pixels but is hidden for phones; the <h3> element in the footer, conversely, shows on phones but is hidden for wider viewports, because it has class visible-xs-block. Similarly, we hide the xylophone image for extra-small viewports with class hidden-xs. We also render the xylophone image responsive - to scale with its parent container's width - by applying class img-responsive.

Lastly, we add a "pills" navigation element in the footer: the button links display horizontally on larger viewports, and stacked vertically on phones. We use some custom CSS, in our jazzcal.css file, to adjust the color and borders of the buttons, overriding the default Bootstrap styles.

A Bootstrap Layout for Pickup Soccer

Duration: 15 to 25 minutes.

In this exercise, you will realize a new design for the Pickup Soccer site using Bootstrap, presenting the site differently for mobile and desktop users. Here are the desktop and phone views of the finished page:

Pickup Soccer design screenshots

For desktop users, let's present the header with a smaller left column, with a tagline and global nav element, and a larger main right column with the title "Pickup Soccer". In the main body of the page we'll show the goal-line/net photo (for desktops and larger) on left and the main body content on right. On phones, we will hide the top tagline and linearize the layout, with the right column sliding under the left column.

  1. Open the file TheBootstrapFramework/Exercises/soccer/index.html in a browser, and open TheBootstrapFramework/Exercises/soccer/index.html and TheBootstrapFramework/Exercises/css/soccer.css in a code editor.
  2. Using the outline and comments provided, add appropriate HTML markup, with the appropriate classes, to layout the page as shown.
  3. Style the "pills" navigation to match the design.
  4. Be sure to render the left image responsively, so that it is constrained to fit the width of its parent container.
  5. Be sure to address the specifications for desktop (top tagline shows, two-column layout) and mobile (bottom tagline shows, one-column layout) from the screen shot above.
  6. Use a custom CSS file to add styles: add the tiled background image (you'll find the image in the images directory) and set the color of the pills navigation buttons to match the rest of the page.
  7. Check your work with both a desktop and mobile browser.

Challenge

Bootstrap offers more complex navigation components, including a "navbar". Try implementing it on our page:

  1. Check out the Bootstrap docs to find the needed code.
  2. Replace the entire contents of the page's <header> element with a navbar, adding appropriate links.
  3. Optionally, you can use logo.png, an image in the images directory, as a logo at the left of the navbar. If you do add the logo image, you may want to remove class="navbar-brand" from the <a> that wraps the image.)
  4. Test your solution with various viewport widths - note how, at narrows browser widths, the navbar automatically collapses into a component more suited for smaller screens.

The finished page should look something like this on desktop and phone browsers:

Pickup Soccer design screenshots

Solution:

TheBootstrapFramework/Solutions/soccer/index.html


  
    
    
    
    
    
    

    Pickup Soccer

    
    

    
    

    
    
  

  
    

Pickup
Soccer

Spring: Time to Move Outside

With the advent of the nicer weather, most of us recreational soccer players move from indoor games to outdoor, grass fields. Here's a few things to keep in mind as you change from the consistent indoor playing surface to the more unpredictable outside pitch:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Find a game. Now.

Code Explanation:

We add a class container to the <header>, <article>, and <footer> elements, and add a <div class="row"> inside the first two. (The <footer>, because it spans the entire width of the screen, does not need <div class="row"> nor the column-classes elements inside of it.)

We use class="col-md-4" and class="col-md-8" to render the narrower and wider columns, respectively, with a narrower left column and wider right column. We again use the justified pills component for navigation.

Classes hidden-xs hidden-sm display the left-side image only for desktop- or large-desktop-width viewports and img-responsive ensures that the image scales to not exceed its parent element's width. Similarly, classes hidden-xs and visible-xs-block hide and display the top and bottom <h3> elements, respectively.

We style the page with our own soccer.css stylesheet, adding the green background image, setting the font size of the <h1> title, and giving the pills elements a green color.

Challenge Solution:

TheBootstrapFramework/Solutions/soccer-challenge/index.html


  
    
    
    
    
    
    

    Pickup Soccer

    
    

    
    

    
    
  

  
   

Spring: Time to Move Outside

With the advent of the nicer weather, most of us recreational soccer players move from indoor games to outdoor, grass fields. Here's a few things to keep in mind as you change from the consistent indoor playing surface to the more unpredictable outside pitch:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Find a game. Now.

Code Explanation:

We copied the example code from http://getbootstrap.com/components/#navbar and pasted it into the <header> of our page. We used the logo.png logo to brand the navbar and added a few sample links. We left in the "search" element from the sample code (though, of course, in our example it doesn't actually perform a search). The navbar nicely shrinks up for smaller-width viewports!