How to Add Twitter Bootstrap to a Rails Application
In this section, we are going to take a break from back-end programming and focus on the UI design portion of the application. Our UI is going to be simple and intuitive and we're going to integrate the Twitter Bootstrap framework to give us a baseline set of styles.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this section, we are going to take a break from back-end programming and focus on the UI design portion of the application. Our UI is going to be simple and intuitive and we're going to integrate the Twitter Bootstrap framework to give us a baseline set of styles.

To start, let's add the Bootstrap Gem to our Gemfile:

# Gemfile

gem 'bootstrap-sass', '~> 3.3', '>= 3.3.6'

Next, open the terminal and type bundle. Once this is done, we have to implement the CSS and JavaScript calls to load the Bootstrap styles.

To get our CSS file configured we need to convert it from a plain CSS file to a SASS file. To accomplish this type this code in the terminal:

mv app/assets/stylesheets/application.css app/assets/stylesheets/application.css.scss

This code is simply changing the file extension from .css to .css.scss to make it easier for us to add some extra functionality and to make the design more user-friendly.

Now, open app/assets/stylesheets/application.css.scss file and add the following code:

/* app/assets/stylesheets/application.css.scss */

@import "bootstrap-sprockets";
@import "bootstrap";
@import "posts.scss";

That's all we need to do the CSS side.

Next, we need to bring in the JavaScript. To do that, open the application.js file and add the code //= require bootstrap-sprockets right after the //= require jquery asset call. This placement is quite important, so make sure it matches my implementation. The reason why the placement is important is because Rails pulls the JavaScript files in order, and if the order if off Bootstrap's JavaScript calls will not function properly.

// app/assets/javascripts/application.js

//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require turbolinks
//= require_tree .

Now, let's start the rails server If you refresh the browser, you can see the font change. Your homepage looks like this now:

medium

You can also open the application.html.erb file and add a class to the body tag like this.

<!-- app/views/layouts/application.html.erb -->

<body class="container">

If you refresh the browser, you can see that the text is now in a container and has margins on the sides of the page. This container class would work only if bootstrap was implemented properly.

Resources