Ruby On Rails Lesson
Bootstrap and Custom CSS
In Section 5.1.1, we associated many of the HTML elements with CSS classes, which gives us considerable flexibility in constructing a layout based on CSS. As noted in Section 5.1.1, many of these classes are specific to Bootstrap, a framework from Twitter that makes it easy to add nice web design and user interface elements to an HTML5 application. In this section, we’ll combine Bootstrap with some custom CSS rules to start adding some style to the sample application.
Our first step is to add Bootstrap, which in Rails applications can be accomplished with the bootstrap-sass gem, as shown in Listing 5.3. The Bootstrap framework natively uses the LESS CSS language for making dynamic stylesheets, but the Rails asset pipeline supports the (very similar) Sass language by default (Section 5.2), so bootstrap-sass converts LESS to Sass and makes all the necessary Bootstrap files available to the current application.5
To install Bootstrap, we run bundle install as usual:
Then restart the web server to incorporate the changes into the development application. The first step in adding custom CSS to our application is to create a file to contain it:
(Use you text editor or IDE to create the new file.) Here both the directory name and filename are important. The directory
is part of the asset pipeline (Section 5.2), and any stylesheets in this directory will automatically be included as part of the application.css file included in the site layout. Furthermore, the filename custom.css.scss includes the .css extension, which indicates a CSS file, and the .scss extension, which indicates a ‘‘Sassy CSS’’ file and arranges for the asset pipeline to process the file using Sass. (We won’t be using Sass until Section 5.2.2, but it’s needed now for the bootstrap-sass gem to work its magic.)
After creating the file for custom CSS, we can use the @import function to include Bootstrap, as shown in Listing 5.4.
Listing 5.4 Adding Bootstrap CSS.
This one line includes the entire Bootstrap CSS framework, with the result shown in in Figure 5.3. The placement of the text isn’t good and the logo doesn’t have any style, but the colors and signup button look promising.
Next we’ll add some CSS that will be used site-wide for styling the layout and each individual page, as shown in Listing 5.5. There are quite a few rules in Listing 5.5; to get a sense of what a CSS rule does, it’s often helpful to comment it out using CSS comments, i.e., by putting it inside /* ... */, and seeing what changes. The result of the CSS in Listing 5.5 is shown in Figure 5.4.
Listing 5.5 Adding CSS for some universal styling applying to all pages.