Foundation and Rails

by Daniel Kehoe

Last updated 4 April 2014

Foundation 5.2 and Rails. How to set up a Rails application with Zurb Foundation. Zurb Foundation provides a standard grid for layout plus dozens of reusable components for page elements such as navigation, forms, and buttons. It gives CSS the kind of structure and convention that makes Rails popular for back-end development. Developers use Foundation to add attractive CSS styling and JavaScript effects to web applications.

A complete rails-foundation example application is available from the RailsApps project. There’s no need to copy code from this article, just use the rails-foundation example application.

If You Are New to Rails

If you’re new to Rails, see What is Ruby on Rails?, the book Learn Ruby on Rails, and recommendations for a Rails tutorial.

Join RailsApps

What is the RailsApps Project?

The RailsApps project provides example applications that developers use as starter apps. Hundreds of developers use the apps, report problems as they arise, and propose solutions. Rails changes frequently; each application is known to work and serves as your personal “reference implementation.” Support for the project comes from subscribers. If this article is helpful to you, please join the RailsApps project to support our work.

What’s Here

This article covers:

  • Installation of Foundation
  • Application Layout
  • Flash Messages
  • Navigation Links

In summary, here are the steps for adding Foundation to a Rails application:

  • add a gem to the Gemfile
  • modify the file app/assets/javascripts/application.js to add Foundation’s Javascript files
  • add the file app/assets/stylesheets/framework_and_overrides.css.scss to add Foundation’s CSS files
  • modify the file app/views/layouts/application.html.erb to change the application layout

Complete instructions are below.

Zurb Foundation Gem

Zurb Foundation is packaged as a gem.

We’ll use the rails_layout gem to generate files for an application layout, navigation links, and flash messages styled with Foundation CSS classes and layout.

In your Gemfile, add:

gem 'foundation-rails'
group :development do
  gem 'rails_layout'

You don’t need the rails_layout gem deployed to production, so put it in the development group.

Run $ bundle install in the Terminal.

Rather than following the installation instructions provided in the Foundation Documentation, we’ll use the rails_layout gem to set up Zurb Foundation and create the files we need. Our approach is slightly different from the Zurb instructions but yields the same results.

Rails Layout Gem

The generator provided by the rails_layout gem will set up Foundation and add the necessary files. Run:

$ rails generate layout:install foundation5 --force

With the --force argument, the rails_layout gem will replace existing files.

The rails_layout gem will rename the file:

  • app/assets/stylesheets/application.css


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

It will create the file:

  • app/assets/stylesheets/framework_and_overrides.css.scss

and modify the file:

  • app/assets/javascripts/application.js

The gem will create or replace four files:

  • app/views/layouts/application.html.erb
  • app/views/layouts/_messages.html.erb
  • app/views/layouts/_navigation.html.erb
  • app/views/layouts/_navigation_links.html.erb

Let’s examine the files to see how our application is configured to use Zurb Foundation.

Renaming the application.css File

The rails_layout gem renamed the app/assets/stylesheets/application.css file as app/assets/stylesheets/application.css.scss. Note the .scss file extension. This will allow you to use the advantages of the Sass syntax for your application stylesheet. Stylesheets can use variables, mixins, and nesting of CSS rules when you use Sass. For more on the advantages of Sass and how to use it, see the Sass website or the Sass Basics RailsCast from Ryan Bates.

Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and is a superset of the CSS syntax. This means that every valid CSS stylesheet is valid SCSS as well. You can use Sass in any file by adding the file extension .scss. The asset pipeline will preprocess any .scss file and expand it as standard CSS.

Before you continue, make sure that the rails_layout gem renamed the app/assets/stylesheets/application.css file as app/assets/stylesheets/application.css.scss. Otherwise you won’t see the CSS styling we will apply.

The application.css.scss File

The Rails asset pipeline will concatenate and compact CSS stylesheets for delivery to the browser when you add them to this directory:

  • app/assets/stylesheets/

The asset pipeline helps web pages display faster in the browser by combining all CSS files into a single file (it does the same for JavaScript).

Let’s examine the file app/assets/stylesheets/application.css.scss:

 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 * You're free to add application-wide styles to this file and they'll appear at the top of the
 * compiled file, but it's generally better to create a new file per style scope.
 *= require_tree .
 *= require_self

The app/assets/stylesheets/application.css.scss file serves two purposes.

First, you can add any CSS rules to the file that you want to use anywhere on your website. Second, the file serves as a manifest, providing a list of files that should be concatenated and included in the single CSS file that is delivered to the browser.

A Global CSS File

Any CSS style rules that you add to the app/assets/stylesheets/application.css.scss file will be available to any view in the application. You could use this file for any style rules that are used on every page, particularly simple utility rules such as highlighting or resetting the appearance of links. However, in practice, you are more likely to modify the style rules provided by Zurb Foundation. These modifications don’t belong in the app/assets/stylesheets/application.css.scss file; they will go in the app/assets/stylesheets/framework_and_overrides.css.scss file.

In general, it’s bad practice to place a lot of CSS in the app/assets/stylesheets/application.css.scss file (unless your CSS is very limited). Instead, structure your CSS in multiple files. CSS that is used on only a single page can go in a file with a name that matches the page. Or, if sections of the website share common elements, such as themes for landing pages or administrative pages, make a file for each theme. How you organize your CSS is up to you; the asset pipeline lets you organize your CSS so it is easier to develop and maintain. Just add the files to the app/assets/stylesheets/ folder.

A Manifest File

It’s not obvious from the name of the app/assets/stylesheets/application.css.scss file that it serves as a manifest file as well as a location for miscellaneous CSS rules. For most websites, you can ignore its role as a manifest file. In the comments at the top of the file, the *= require_self directive indicates that any CSS in the file should be delivered to the browser. The *= require_tree . directive (note the Unix “dot operator”) indicates any files in the same folder, including files in subfolders, should be combined into a single file for delivery to the browser.

If your website is large and complex, you can remove the *= require_tree . directive and specify individual files to be included in the file that is generated by the asset pipeline. This gives you the option of reducing the size of the application-wide CSS file that is delivered to the browser. For example, you might segregate a file that includes CSS that is used only in the site’s administrative section. In general, only large and complex sites need this optimization. The speed of rendering a single large CSS file is faster than fetching multiple files.

Zurb Foundation JavaScript

Zurb Foundation provides both CSS and JavaScript libraries.

Like the application.css.scss file, the application.js file is a manifest that allows a developer to designate the JavaScript files that will be combined for delivery to the browser.

The rails_layout gem modified the file app/assets/javascripts/application.js to include the Foundation JavaScript libraries:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require foundation
//= require_tree .
$(function() {

It added the directive //= require foundation before //= require_tree ..

The last three lines use jQuery to load the Foundation JavaScript libraries after the browser has fired a “DOM ready” event (which means the page is fully rendered and not waiting for additional files to download).

$(function() {

Zurb Foundation CSS

The rails_layout gem added a file app/assets/stylesheets/framework_and_overrides.css.scss containing:

// import the CSS framework
@import "foundation";

The file app/assets/stylesheets/framework_and_overrides.css.scss is automatically included and compiled into your Rails application.css file by the *= require_tree . statement in the app/assets/stylesheets/application.css.scss file.

The @import "foundation"; directive will import the Foundation CSS rules from the Foundation gem.

You could add the Foundation @import code to the app/assets/stylesheets/application.css.scss file. However, it is better to have a separate app/assets/stylesheets/framework_and_overrides.css.scss file. You may wish to modify the Foundation CSS rules; placing changes to Foundation CSS rules in the framework_and_overrides.css.scss file will keep your CSS better organized.

Using Sass Mixins with Foundation

In addition to the simple @import "foundation"; directive, the app/assets/stylesheets/framework_and_overrides.css.scss contains a collection of Sass mixins. These are examples that you can remove.

You can use Sass mixins to map Foundation class names to your own semantic class names. The rails_layout gem provides examples of Sass mixins that apply CSS style rules to the default application layout. In doing so, the default application layout is free of framework-specific code and can be used with Zurb Foundation, Bootstrap, or other front-end frameworks. The book Learn Ruby on Rails explains how to use Sass mixins.

Using Foundation CSS Classes

Now that you’ve installed Zurb Foundation, you have a rich library of interactive effects you can add to your pages.

Take a look at the Foundation documentation to see your options. Here are just a few examples:

At a simpler level, Foundation provides a collection of carefully-crafted styling rules in the form of CSS classes. These are building blocks you use for page layout and typographic styling. For example, Foundation gives you CSS classes to set up rows and columns in a grid system.

Let’s take a closer look at the Foundation grid system.

Foundation Grid

By default, the Foundation grid is 940 pixels wide. Two grids are available; “small” for browsers less than 768 pixels in width, and “large” for all others. Start by designing for the small screen with the classes prefixed “small”; then add classes prefixed “large” to change the layout for a large screen. The layout will change when the browser width is less than 768 pixels wide.

The grid gives you 12 columns by default. You can organize your layout in horizontal and vertical sections using row and columns classes.

For example, you could use Foundation grid classes to set up an application layout with a footer as a row with two sections:

<footer class="row">
  <section class="small-4 columns">
    Copyright 2013
  <section class="small-8 columns">
    All rights reserved.

The Foundation row class will create a horizontal break. The footer will contain two side-by-side sections. The first will be four columns wide; the second will be eight columns wide.

To better understand the grid system with all its options, see the documentation for the Foundation Grid.

Application Layout with Zurb Foundation

Generating a new Rails application with the rails new command will create a default application layout. Rails will use the layout defined in the file app/views/layouts/application.html.erb as a default for rendering any page.

Let’s look at the application layout file created by the rails_layout gem:

Examine the contents of the file app/views/layouts/application.html.erb:

<!DOCTYPE html>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= content_for?(:title) ? yield(:title) : "Rails Foundation" %></title>
    <meta name="description" content="<%= content_for?(:description) ? yield(:description) : "Rails Foundation" %>">
    <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
    <%# Modernizr is required for Zurb Foundation %>
    <%= javascript_include_tag "vendor/modernizr" %>
    <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
    <%= csrf_meta_tags %>
      <%= render 'layouts/navigation' %>
    <main role="main">
       <%= render 'layouts/messages' %>
       <%= yield %>

The book Learn Ruby on Rails covers the application layout file in detail.

If you use the Sass mixins provided by the rails_layout gem in the app/assets/stylesheets/framework_and_overrides.css.scss file, there’s no need to use Foundation classes directly in the application layout (Foundation classes will be applied to the HTML element main).

If you don’t use Sass mixins, you can add Foundation classes directly to the application layout. For example, you might set the main element to be twelve columns wide using Foundation classes:

<main role="main" class="small-12 columns">

See the documentation for the Foundation Grid.

Modernizr JavaScript Library

The application layout file includes:

<%# Modernizr is required for Zurb Foundation %>
<%= javascript_include_tag "vendor/custom.modernizr" %>

The Modernizr JavaScript library is a prerequisite for Foundation. Modernizr makes it possible for older browsers to use HTML5 elements. It also detects mobile devices. It must be loaded before Foundation, so it is included above javascript_include_tag "application".

Flash Messages with Zurb Foundation

Rails provides a standard convention to display alerts (including error messages) and other notices (including success messages), called a flash message. The name comes from the term “flash memory” and should not be confused with the “Adobe Flash” web development platform that was once popular for animated websites.

Rails uses :notice and :alert as flash message keys. Foundation provides a base class alert-box with additional classes success and alert. A bit of parsing is required to get a Rails “notice” message to be styled with the Foundation success style. Any other message, including a Rails “alert” message, will be styled with the Foundation alert style.

By default, Foundation applies a green background to success and a red background to alert. Foundation provides additional classes info (blue) and warning (amber). With a little hacking, it’s possible to create a Rails flash message with a custom name, such as :info, that will display with the Foundation info class. However, it’s wise to stick with the Rails convention of using only “alert” and “notice.”

You can include code to display flash messages directly in your application layout file or you can create a partial.

The application layout file includes a messages partial:

<%= render 'layouts/messages' %>

Examine the file app/views/layouts/_messages.html.erb:

<%# Rails flash messages styled for Zurb Foundation %>
<% flash.each do |name, msg| %>
  <% if msg.is_a?(String) %>
    <div data-alert class="alert-box round <%= name.to_s == 'notice' ? 'success' : 'alert' %>">
      <%= content_tag :div, msg %>
      <a href="#" class="close">&times;</a>
  <% end %>
<% end %>

We use each to iterate through the flash hash, retrieving a name and msg that are passed to a block to be output as a string. The expression if msg.is_a?(String) serves as a test to make sure we only display messages that are strings. We construct a div that applies Foundation CSS styling around the message. Foundation recognizes a class alert-box and round (for rounded corners). A class of either success or alert styles the message. Rails notice messages will get styled with the Foundation success class. Any other Rails messages, including alert messages, will get styled with the Foundation alert class.

We use the Rails content_tag view helper to create a div containing the message.

Finally, we create a “close” icon by applying the class close to a link. We use the HTML entity &times; (a big “X” character) for the link; it could be the word “close” or anything else we like. Foundation’s integrated JavaScript library will hide the alert box when the “close” link is clicked.

Foundation provides detailed documentation if you want to change the styling of the alert boxes.

Navigation Partial with Zurb Foundation

The layout and styling required for the Foundation navigation bar are in the navigation partial file.

The application layout file includes a navigation partial:

<%= render 'layouts/navigation' %>

Examine the file app/views/layouts/_navigation.html.erb:

<%# navigation styled for Zurb Foundation 5 %>
<nav class="top-bar" data-topbar>
  <ul class="title-area">
    <li class="name"><%= link_to 'Home', root_path %></li>
    <li class="toggle-topbar menu-icon"><a href="#">Menu</a></li>
  <div class="top-bar-section">
      <%= render 'layouts/navigation_links' %>

The navigation partial includes layout and Foundation classes needed to produce a responsive navigation bar.

The responsive navigation bar adjusts to different browser widths. At small sizes, the navigation links will disappear and be replaced by an icon labeled “Menu.” Clicking the icon will reveal a vertical menu of navigation links. The navigation menu is a great demonstration of the ability of Zurb Foundation to adjust to the small screen size of a tablet or smartphone.

If you’d like to add a site name or logo to the tutorial application, you can replace the link helper <%= link_to 'Home', root_path %>. It is important to preserve the enclosing layout and classes, even if you don’t want to display a site name or logo. The enclosing layout is used to generate the navigation menu when the browser window shrinks to accommodate a tablet or smartphone.

We wrap the nested partial render 'layouts/navigation_links' with a Foundation class to complete the navigation bar.

Navigation Links Partial

The file app/views/layouts/_navigation_links.html.erb is very simple:

<%# add navigation links to this file %>

You can add links to this file, for example:

<%# add navigation links to this file %>
<li><%= link_to 'About', page_path('about') %></li>
<li><%= link_to 'Contact', new_contact_path %></li>

The navigation links partial is simply a list of navigation links. It doesn’t require additional CSS styling. By separating the links from the styling that creates the navigation bar, we segregate the code that is unique to Zurb Foundation. In the future, if the Zurb Foundation layout or CSS classes change, we can make changes without touching the navigation links.

Set up SimpleForm with Zurb Foundation

Rails provides a set of view helpers for forms. They are described in the RailsGuides: Rails Form Helpers document. Many developers use an alternative set of form helpers named SimpleForm, provided by the SimpleForm gem. The SimpleForm helpers are more powerful, easier to use, and offer an option for styling with Zurb Foundation.

In your Gemfile, add:

gem 'simple_form'

Run $ bundle install.

Run the generator to install SimpleForm with a Zurb Foundation option:

$ rails generate simple_form:install --foundation

which installs several configuration files:


Here the SimpleForm gem uses the rails generate command to create files for initialization and localization (language translation). SimpleForm can be customized with settings in the initialization file.

Themes for Zurb Foundation

Frameworks such as Foundation are intended to provide the building blocks for a custom website design. If you’ve got strong design skills, or can partner with an experienced web designer, you can develop a custom design that expresses the purpose and motif of your website. If you don’t have the skill or resources to customize the design, you can use the generic Foundation design.

An alternative is to purchase a pre-designed theme for your website. Here are sites that offer pre-built themes for sale:

You can design your own pages using Foundation, or customize a theme, with a drag-and-drop design tool:

Resources for Zurb Foundation

Zurb provides a collection of example layouts:

Find contributed examples of Foundation layouts and design elements here:

Zurb maintains a list of Foundation third-party tools and projects:

Getting Help for Zurb Foundation

Zurb has a community forum for questions and answers:

Stack Overflow is a popular site for questions and answers about Zurb Foundation.

Did You Like the Article?

Was the article useful to you? Follow @rails_apps on Twitter and tweet some praise. I’d love to know you were helped out by the article.

You can also find me on Facebook or Google+.


Is this helpful? Your encouragement fuels the project. Please tweet or add a comment. Couldn't get something to work? For the example apps and tutorials, it's best to open an issue on GitHub so we can help you.

comments powered by Disqus