Advertisement

Going Off Canvas with Zurb Foundation 3.0

by

The hottest trend in the industry today is almost certainly responsive webdesign (RWD). Every day new approaches appear which redefine the way that we think about websites responding to different devices including desktops, tablets and phones. Today we're going to be diving head first into the newest RWD pattern on the block, off-canvas layouts - a very clever approach from the team at Zurb.

In this tutorial, we're going to be creating a simple homepage that has some very special features when viewed on a smaller viewports. While we're going to be working step by step to create the page, we will be getting Zurb Foundation and the Off-Canvas Layouts to do all the heavy lifting for us.

Ready to get started?


A Few Things Before we Start

As I mentioned, we're going to be building our site based on the hot-off-the-press Zurb Foundation 3.0. Foundation is an advanced responsive front end framework that is often compared to Twitter Bootstrap (Which we have covered here before on Webdesigntuts+). While it's not completely necessary to have used Foundation before, I strongly recommend that you review the Foundation documentation, in particular the Grid section, before you get started on this tutorial.

Secondly, we're not going to be following strict best practices in this tutorial, for the sake of brevity and clarity. For example, we're going to be over-riding the base styles with our own stylesheet, which will have some (very minimal) impacts on performance and an extra HTTP request. I'll be making comments throughout the article whenever another approach may be a better alternative for a production site.

As a quick note on terminology, I'll be referring to the viewport when describing the size of the browser. For example, a 'small viewport' in the context of this tutorial will refer to a browser size (or device) smaller than 768px.

Finally, in the code sections of the tutorial, I'll only be including the -webkit brower prefix where relevant for the sake of brevity. In the downloadable files, all of the browser prefixes will be included.

With all that said, let's take a look at how we're going to be approaching this project.


The Plan Of Attack

Rather than laying out all of our markup first and then returning to style it via CSS - which would quickly get confusing - we're going to build the page in small chunks, starting with our general markup and then fleshing out and styling each section as we progress.

We're going to be approaching the project like this:

  • Download all of the required files and setup our file tree.
  • Setup the base HTML and CSS.
  • Markup and style the components of the desktop version of the site (i.e. wide viewport size), one by one.
  • Hookup the off-canvas components.
  • Add and override some media queries to enhance the look of the site for small viewports.
  • Look under the hood at what powers the layout.

Step 1: Download the Framework

As we've already discussed, this page is going to be based upon Foundation 3.0 and the off-canvas layouts, both developed by Zurb.

First, head over to the Foundation website and download the latest version. We'll be using the complete download package in this tutorial (but you could also create your own custom build if you prefer).

Next, we'll need to download the off-canvas layouts from the Zurb Playground.

Unzip both files, but don't combine them just yet - we will need to tweak the document tree, which we'll be covering in Step 3 in a few moments.


Step 2: Download Page Assets

We'll be using a few images and assets in our project. Download and extract the source files to use what you see in the demo. The images for the slides are just placeholders however, so you might think about something a little more dynamic to spice things up.


Step 3: Setup the File Tree

Now that we have all of the required files, stylesheets and scripts, let's combine these into a single folder so that we can start getting our hands dirty.

We have to do a little renaming and tweaking here, so be careful to follow these next steps closely:

1. Create a new folder on your desktop and move across the contents of the extracted Foundation 3.0 folder.

2. Rename the index.html file to 'default.html'.
Create a new folder called 'misc' and move the license, robots and humans text files (just to keep everything neat and tidy).

3. From the offcanvas folder that you have downloaded and extracted, move the following files into your main project folder:

  • offcanvas-2.html → root
  • css/offcanvas.css → /stylesheets/
  • js/jquery.offcanvas.js → /javascripts/

4. Create a new folder under 'images' and name it 'site_assets'. Copy across the image files downloaded from the resources (see Step Two.)

5. Create a new folder called 'fonts' and move across the custom font files downloaded in Step Two.

6. Finally, create the following new files:

  • index.html
  • /stylesheets/style.css

Note: there are several files in the javascripts folder that we won't be using in this project. I've left them in, in case you want to build upon our base and explore the other features of Foundation. For the record, this tutorial requires the following .js files - feel free to delete the remaining scripts:

  • app.js
  • jquery.min.js
  • jquery.offcanvas.js
  • jquery.orbit-1.4.0.js
  • modernizer.foundation.js


Step 4: Lay Down the HTML Markup

As mentioned already, we're going to be building our page piece by piece, but I do want to make sure that we have a plan to build upon. As such, let's markup our index.html page so we know where we are headed in the following steps.

First, let's setup our <head> and <body> and link up all of the required stylesheets and scripts:

index.html

<!DOCTYPE html> 
<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ --> 
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> 
<!--[if IE 7]>    <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]--> 
<!--[if IE 8]>    <html class="no-js lt-ie9" lang="en"> <![endif]--> 
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> 
<head> 
  <meta charset="utf-8" /> 
 
<!-- Set the viewport width to device width for mobile --> 
  <meta name="viewport" content="width=device-width" /> 
 
<title>Off Canvas Layout With Zurb Foundation</title> 
 
<!-- Included Foundations CSS Files --> 
  <link rel="stylesheet" href="stylesheets/foundation.css"> 
  <link rel="stylesheet" href="stylesheets/offcanvas.css"> 
 
<!-- Included Custom CSS Files --> 
  <link rel="stylesheet" href="stylesheets/style.css"> 
 
<!--[if lt IE 9]> 
    <link rel="stylesheet" href="stylesheets/ie.css"> 
  <![endif]--> 
 
<!-- Include Gooogle Webfonts --> 
  <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600' rel='stylesheet' type='text/css'> 
 
<script src="javascripts/modernizr.foundation.js"></script> 
 
<!-- IE Fix for HTML5 Tags --> 
  <!--[if lt IE 9]> 
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> 
  <![endif]--> 
 
</head> 
 
<body id="page"> 
 
<!-- HEADER --> 
 
<!-- SLIDER --> 
 
<!-- CALLOUT --> 
 
<!-- SERVICES --> 
 
<!-- FEATURED PROJECT --> 
 
<!-- CONTACT US --> 
 
<!-- FOOTER --> 
 
 
<!-- Include JS Files --> 
 
<script src="javascripts/jquery.min.js"></script> 
<script src="javascripts/foundation.js"></script> 
<script src="javascripts/apps.js"></script> 
<script src="javascripts/jquery.orbit-1.4.0.js"></script> 
<script type="text/javascript" src="javascripts/jquery.offcanvas.js"></script> 
 
 
</body>

While everything here should be fairly self explanatory, let's quickly run through the code:

  • The HTML5 doctype has been set.
  • Added some conditional rules for older versions of Internet Explorer.
  • Changed the viewport width (i.e. the width of the browser window) to the width of the device for phones.
  • We've linked up the stylesheets that we'll be using during this project, including an 'IE8 and under only' stylesheet Note, you'd ideally want to combine and minify these stylesheets for a production site.
  • We'll be using the 'Open Sans' webfont from Google Webfonts in this project. We've included a call to this font in three different weights (300, 400 and 600). View the Open Sans font family.
  • We've included a link to the modernizer script and the HTML5 shiv for IE8.
  • In the body of the document I've added in some comments to indicate the final structure of the markup.
  • Finally, we've linked to our javascript files, including jQuery, Foundation, Orbit (the Foundation slider that we'll be using in this project), and of course, our off-canvas script that will help with the final effects that we're trying to achieve.

Easy peasy so far, right? Let's set up our CSS stylesheet and add a few base styles.


Step 5: Set Up the CSS

Before creating our own style.css stylesheet, we want the ability to read the foundation.css stylesheet (even though we won't be making any changes to it). As the downloaded foundation.css file is served to us minified (i.e. no white space, no trailing semi-colons and no line breaks), it's not very readable at the moment.

To solve this problem, we need to 'unminify' the CSS:

  1. Open up the foundation.css stylesheet in your code editor of choice and copy the entire contents to your clipboard.
  2. Head over to Peter Coles' Online CSS Unminifier.
  3. Paste the copied text into the first window on the site and click the 'Unminify' button.
  4. In the second window that appears, copy all the text to your clipboard.
  5. Return to the foundation.css file, and copy the clipboard text over the top of the file.
  6. Save the document with the same filename and location (/stylesheets/foundation.css)

As the unminified foundation.css is around 2800 lines, we're not going to waste time by navigating the entire file to make changes and insert new styles. Instead, we've already created our own stylesheet called 'style.css' that we will be including new styles and over-riding the base styles set out by foundation.css.

Open up style.css from your stylesheets folder and add the following code:

@charset "UTF-8"; 
 
/* `Main Styles and Grid Overrides 
----------------------------------------------------------------------------------------------------*/ 
/* Set some colors that will be used in the layout */ 
body {background-color:#201A16;} 
 
.color-one {background-color: #4A456C;} /* light purple */ 
.color-two {background-color:#353153 ;} /* dark purple */  
.color-three {background-color: #201A16;} /* brown */ 
.color-four {background-color:#755F4F ;} /*light brown*/ 
.color-five {background-color:#dddddd;} /*dark gray */ 

section { 
    padding:0; 
    margin:0; 
    /* Prevents horizontal scrollling for off-canvas elements */ 
    overflow-x: hidden; 
} 
 
/* Set the width of the site rows */ 
.row { 
    width:1024px; 
} 
 
/* Make sure that the bands stretch to 100% width */ 
.full-width, .site-footer { 
    min-width:100%;  
    position: relative;  
    z-index:9999; 
} 
 
 
/* `PRIMARY NAVBAR 
----------------------------------------------------------------------------------------------------*/ 
 
/* `TYPOGRAPHY 
----------------------------------------------------------------------------------------------------*/ 
 
h2, h3 { 
    font-family:'Open Sans', sans-serif; 
    text-align:center; 
    color:white; 
    font-size:2em; 
    font-weight:600; 
} 
 
h3 { 
    font-size:1.7em; 
    position: relative;} 
 
p { 
    color:white; 
    font-size: 1.3em; 
    font-family: 'Open Sans', sans-serif; 
    font-weight: 300; 
} 
 
 
/* `BUTTONS 
----------------------------------------------------------------------------------------------------*/ 
 
/* `FORMS 
----------------------------------------------------------------------------------------------------*/ 
 
/* `LAYOUT 
----------------------------------------------------------------------------------------------------*/ 
 
/* `OFF CANVAS 
----------------------------------------------------------------------------------------------------*/ 
 
 
/* `MEDIA QUERIES 
----------------------------------------------------------------------------------------------------*/

At this stage, all we have done is created some structure to the stylesheet to help us keep everything organized and logical in the later steps (as defined by the CSS comments), and added a selection of style overrides and some color classes that we will be using in the initial steps.

You'll note that color classes have been added (e.g. .color-one) to our styles. While we could build the colors directly into the page section selectors as we go, this approach allows us to easily modify colors in a single place, as well as giving us a reusable class that can be used to style any elements background anywhere in the page.

Another thing to note is that instead of describing the color classes with their color (e.g. .dark-purple), they are completely non-presentational, allowing us to change the colors at any time or even reuse the code in another project without being locked in to presentational class names.

I've also removed the default padding from the section elements as we'll be creating a full width layout.

The default .row class set in foundation.css is 1000px, which is a tad too narrow for our layout. We've changed this to 1024px.

Next, I've added a .full-width class that will allow us to create our 100% width section 'bands' in our layout.

Finally, under the 'Typography' section, I've also set some base styles for our header and paragraph elements.

Columns? Rows? Full Width classes? Confused? Don't be. Let's take a flyby review of how Foundation works.


Step 6: A Five Minute Review of Foundation

You have read the Foundation documentation, and have an understanding of how a Foundation page is structured, right?

No? Let's get you up to speed.

A webpage built with Foundation follows a set format that allows you to create a multi columned, responsive layout very quickly and very easily.

The following diagram gives you an overview of the general structure that we'll be using today:

This is a very simplified overview, but it will serve our purposes to explain the Foundation grid system.

Firstly, Foundation 2 requires a container div to wrap all of its child content within. This requirement has been removed in the latest code base of Foundation 3.0, meaning that row divs can be included directly under the <body> tags.

Secondly, to achieve our colored 'bands', each section is wrapped in a div with a class of .fullwidth. The background color will be added in with an additional class (.color-one, .color-two, etc.), which we added in the previous step.

Next, each part of the site is wrapped in a div with a class of .row In the last step, we set the width of the row div at 1024px. In fact, we could set this width at any width to suit our needs and the Foundation grid adapts to the width without us needing to change any other CSS.

Contained in each .row div are up to twelve divs with a class of .column, depending on the layout you want to achieve. So, for example, for content that stretches the full width of the row, we would use apply the classes of .twelve .columns. In the second example (which is representative of a page with a main content area and a side bar), inside our row you would have two divs, one with a classes of .eight .columns and another with classes of .four .columns.

When the browser window is resized to a smaller viewport (or a small device is used to view the site), the columns automatically stack on top of one other as per the rules set out in foundation.css stylesheet - that's right… with just a little bit of markup, your site is automatically responsive (cool, huh?).

Finally, in the last example in the above image, we can center a column horizontally within the row by applying the additional class .centered (note, this only centers the div, not the content inside it).

To make these concepts clearer, let's code the three examples in the image:

 
    <!-- example one --> 
    <div class="full-width color-one"> 
        <div class="row"> 
            <div class="twelve columns"> 
 
                <!-- ...content goes here... --> 
 
            </div><!-- end twelve columns --> 
        </div><!-- end row --> 
    </div><!-- end full-width --> 
 
    <!-- example two --> 
    <div class="full-width color-two"> 
        <div class="row"> 
            <div class="eight columns"> 
 
                <!-- ...content goes here... --> 
 
            </div><!-- end eight columns --> 
 
            <div class="four columns"> 
 
                <!-- ...content goes here... --> 
 
            </div><!-- end four columns --> 
        </div><!-- end row --> 
    </div><!-- end full-width -->    
 
    <!-- example three --> 
        <div class="full-width color-three"> 
            <div class="row"> 
                <div class="eight columns centered"> 
 
                    <!-- ...content goes here... --> 
 
                </div><!-- end eight columns --> 
            </div><!-- end row --> 
        </div><!-- end full-width -->

An important concept to understand about the Foundation grid system is that column widths are measured in percentages, meaning that they automatically adjust to fill the row (or nested row) that they are children of.

Another thing that is very important to note is that columns stretch to 100% of the width of the row - in fact, the Foundation grid system uses box-sizing on all elements, so there is no padding or margins between columns (the spacing in the image above is only representational to illustrate the broad concepts of the grid system).

It should also be noted that you are able to nest infinite rows within columns (well, within reason, anyway). While we won't be doing much nesting of rows within columns in this tutorial, this is a very powerful layout technique and gives the ability to create extremely sophisticated layout patterns.

Still confused, or you'd like to delve into the grid system some more? I highly recommend that you review the extensive documentation on the Foundation site.

And with that whistlestop tour of the basics of the Foundation grid system, let's get into some code!


Step 7: Markup the Header Section

For our header, we want a logo to the left of the page and a simple navigation bar that will float to the right side of the page. When the viewport of the browser or the device reaches a width of 768px and under, we want a number of things to happen:

  1. The logo will be the topmost element of the site, and will remain aligned left to the browser window.
  2. The navigation bar will become hidden.
  3. Two buttons will appear that will give access to the small-viewport navigation menu and the off-canvas elements of the site.
  4. When the menu button is pressed, a mobile navigation menu will dropdown from the top of the screen.
  5. When the 'off-canvas' button (as we will call it for now) is pressed, the main screen will move to the right and a supplemental panel will slide out from the left of the panel.

We will be tackling steps four and five later on in the tutorial, but we have everything that we need baked right into Foundation to achieve steps one to three.

First, since we know that our logo and our navigation bar will occupy two ends of the same row, we can easily lay this out with the .row and .column classes discussed in the last step.

In your index.html file, add the following code directly under the header comment (underneath the <body>) tag:

 
    <div class="first full-width color-three"> 
 
        <header id="header" class="row">     
 
            <!-- LOGO --> 
            <div class="five columns"> 
                <a href="#" class="logo"><img src="images/site_assets/logo.png" /> 
                <h1 class="hide-for-small">Off Canvas</h1></a> 
            </div> <!-- end five columns --> 
 
            <!-- LARGE VIEWPORT NAVIGATION --> 
            <div class="seven columns"> 
                <nav id="menu" class="hide-for-small"> 
                    <ul id="mainNav" class="nav-bar"> 
                        <li><a href="" class="main">Home</a></li> 
                        <li><a href="" class="main">About</a></li> 
                        <li><a href="" class="main">Services</a></li> 
                        <li><a href="" class="main">Blog</a></li> 
                        <li><a href="" class="main">Contact</a></li>                             
                    </ul>                                            
                </nav> 
 
            <!-- SMALL SCREEN EXTRAS BUTTONS --> 
                <p class="show-for-small"> 
                <a class='menu-button button' id="menuButton" href="#menu">Menu</a><!-- link goes to named anchor --> 
                <a class='sidebar-button button' id="sidebarButton" href="#contact" >Contact Us</a> 
                </p>
                
<!-- link goes to named anchor --> 
            </div><!-- end seven columns --> 
 
        </header>    
    </div><!-- end full width --> 
 
    <!-- All other site components 
        ... 
            ... 
                ... -->

There are a few things to comment on in this code block - including the utilization of a number of Foundation's features.

First, you'll notice that we have wrapped our logo in a div with a class of .five .columns and our navigation bar (and the extras) in a .seven .columns div, as per our introduction to the grid system in Step Six.

As I mentioned, at smaller screen sizes, we want the main navigation to be hidden from view. Using Foundation, this is as simple as adding the class .hide-for-small, which effectively sets display: block; in viewports greater than 767px sets display: none; for the element in smaller viewports (take a look at the unminified foundation.css code from line 547 – 565 for a better understanding of this).

In the opposite way, the two buttons in the 'small screen extras' section are hidden from view on large screens (>767px) and displayed on smaller screens by adding the .show-for-small class to the <p> element.

We've also added some ids to the small screen buttons that will help us in the later stages of the tutorial.

Make sure that the the footer tag is closed right above our javascripts and <body&rt; tag at the bottom of the page - all of the markup for the remaining site components will be wrapped in this div.

Now that we have established the markup, let's style the individual components.

In your style.css file, under the 'Layout' section, add the following code:

/* HEADER */ 
 
.logo { 
    position: relative; 
    top:20px; 
} 
 
 
.logo img { 
    /* Remove border in ie */ 
    border:none; 
} 
 
.first { 
    /* add the border under the header */ 
    border-bottom: 5px solid #755F4F; 
} 
 
header { 
    min-height: 100px; 
}

You'll see that there is nothing too groundbreaking here. We've simply set a minimum height for the <header>, added a 5px border to the full width div with the inclusion of the .first class and set some basic positioning for the logo.

Currently, the <h1> element sits on top of the logo image. We'll want to remove the this header from view but still include it in the markup for SEO and accessibility purposes.

Under the 'Typography' section of style.css, add in the following code:

h1 { 
    /* remove h1 text from the viewport */ 
    font: 0/0 a;
    text-shadow: none;
color: transparent; 
}

Here, we've set the h1 to a font size and line height of 0%, removed any legacy text shadow and removed any text color.

Next, we'll style our navigation menu.


Step 8: Style the Navigation Menu

Under the 'Primary Navbar' section of the style.css stylesheet, add in the following code:

/* nav bar floats to the right of the row */  
#mainNav {float:right;} 
 
 
.nav-bar { 
/* override foundation styles */     
    background-color:transparent; 
    border:none;  
} 
 
.nav-bar > li { 
    /* removes borders */ 
    box-shadow:0 0 0 0; 
    border:none; 
    /*centers nav bar to the logo */ 
    line-height: 60px; 
    background-color:#201a16; 
    -webkit-transition:all .2s ease-in-out; 
} 
 
.nav-bar>li:last-child { 
    border:none; 
    /* removes borders */ 
    box-shadow:0 0 0 0;  
}  
 
.nav-bar > li:hover { 
    border-bottom: 4px white solid; 
    -webkit-transition:all .2s ease-in-out; 
    box-shadow: 0 1px 3px rgba(0, 0, 0, .4) inset; /* Opera 10.5, IE9, FF4+, Chrome 6+, iOS 5 */ 
    background-color:#110E0C; 
} 
 
.nav-bar > li a { 
    border:none; 
    font-family: 'Open Sans', sans-serif; 
    font-weight: 400; 
    /* px used instead of em to ensure nav bar doesn't break into multiple lines */ 
    font-size: 15px !important;  
}

In this CSS, we are taking the base styles from foundation and applying style more suited to our design.

The default styles in Foundation create borders for the navigation <li> elements in two ways, first by applying a 'border-left' attribute and secondly by applying a 1px box shadow. Since we don't want any borders, both the border and box-shadow attributes need to be set to 0.

In addition to the base styling, I've also added a simple transition to the hover state of the <li> items that adds a little polish to the menu. It's also worth pointing out that as well as applying the transition to the hover state, I've also applied the same transition to the normal state, so when the mouse hovers off the element, the effect 'rewinds'.

The only other thing of note in this code block is the use of pixels instead of ems for the link elements. While it's often a good idea to use ems (or rems) for text elements in your projects to allow users to define their own text size, in this case we want to ensure that users can't resize their text so as not to break the layout of the navigation bar (of course we can't do anything about zooming, however!).

We also need to style the small-screen-extras buttons.

In the 'Buttons' section of your style.css stylesheets, apply the following code:

.button { 
    background-color:#dddddd; 
    border-color: #cccccc; 
    color:#222222; 
} 
 
.button:hover { 
    background-color: #bbb; 
    box-shadow: 0px 0px 10px rgba(0, 0, 0, .8) inset; /* Opera 10.5, IE9, FF4+, Chrome 6+, iOS 5 */ 
    border-color: #444444; 
    color:#222222; 
} 
 
.button:focus { 
    -webkit-box-shadow: 0 0 4px #ffffff, 0 1px 0 rgba(255, 255, 255, 0.5) inset; 
    -moz-box-shadow: 0 0 4px #ffffff, 0 1px 0 rgba(255, 255, 255, 0.5) inset; 
    box-shadow: 0 0 4px #2ba6cb, 0 1px 0 rgba(255, 255, 255, 0.5) inset; 
    color: #222; 
}

All we are doing here is building upon the existing styling from foundation.css. What that means is that we need to change some colors and we can still take advantage of all of Foundation's sweet transitions.

Note: these changes will flow on to any other buttons in the page. If we wanted a button of a different color later on (for example a submit button), we could easily target it with an additional class name.

Great! That's our header finished (for the moment). If you resize your browser window, you'll be able to see Foundation in action. Of course, our small-screen-extra buttons don't do anything (yet).


Step 9: The Slider

For the next section of the site, we'll be adding a simple slider that will scroll through three full-width images. In addition, the slider width will resize to the width of the border, and will also become hidden on screens smaller than 767px.

Sounds complicated? Actually, it's quite simple. We'll be using Foundation's built in slider "Orbit" plugin which is extremely easy to hook up and customize to meet our needs.

Under the 'Slider' section in your index.html file, add in the following code:

<div class="full-width"> 
    <div class="hide-for-small"> 
        <div id="featured">  
            <img src="images/site_assets/slide1.jpg" alt="" /> 
            <img src="images/site_assets/slide2.jpg"  alt="" /> 
            <img src="images/site_assets/slide3.jpg" alt="" /> 
        </div> 
    </div> <!-- end hide-for-small --> 
</div><!-- end full width -->

You'll see here that we've wrapped the slider (with an id of "featured") in a div with a class of .hide-for-small that will change the slider to display: none; for screen sizes <767px. Both of these divs are wrapped in a .full-width div.

Styling the slide show couldn't be easier. In your style.css stylesheet, add the following CSS under the 'Layout' section:

/* SLIDER */ 
#featured > img {width:100%;}

Finally, we need to call the Orbit jQuery script. At the bottom of your document before the </body> tag, add the following script:

<!-- Call Slideshow --> 
<script type="text/javascript"> 
        $(window).load(function() { 
        $('#featured').orbit(); 
    }); 
</script>

Before we move on, there's just a couple of quick things that I'd like to mention.

Firstly, depending on your Foundation build, you may need to change the file path of the Orbit images (arrows, timers, bullets, etc.) to the correct location in your file tree (../images/foundation/orbit/..). You can do this quite simply by completing a find / replace in your foundation.css stylesheet, or update them manually between lines 2448 and 2659 of the unminified foundation.css file.

Secondly, we won't be customizing the slider past the base styles. There are a bunch of different options, transitions and more that you can apply to the slider. To learn more about extending the Orbit slider, refer to the Foundation Orbit Documentation.

Thirdly, I'd like to point out that there would be performance issues with this solution for small screens if put into the wild. The .hide-for-small class simply sets display: none;, and does not actually stop the device from downloading the images. This means that a mobile phone on cellular data would be downloading three sizable images for - essentially - nothing.

This is a tricky topic and is out of scope for this tutorial, however a possible solution may be to use AJAX to load in the images for large screen sizes.


Step 10: The Callout Section

The next step is to add a simple callout or slogan to the site underneath the slider.

Under the 'Callout' section in the index.html, add the following code:

<div class="full-width color-five"> 
    <div class="row callout"> 
        <div class="twelve columns"> 
        	<p>We make incredible websites for incredible companies.</p> 
        </div><!-- end columns --> 
    </div><!-- end row --> 
</div><!-- end full width color five -->

In this HTML we've set up a full width column div .twelve .columns, and added a class of .callout to the row that will allow us to style the callout text.

Next step is to add some styling for the </code> element.

Under the 'Typography' section of the style.css stylesheet, add the following code:

/* CALLOUT PANEL */ 
 
.callout p {  
    font-family:'Open Sans', sans-serif; 
    text-align:center; 
    font-size:2em; 
    font-weight:600; 
    color:#222222; 
    margin-bottom: 0; 
}

Note: all of these attributes except for color and margin-bottom are identical to the h1, h2 & h3 selectors that we have already defined. While it's fine to add the .callout p selector to this stack, I've chosen to define it separately in case we would want to either change the style of any of these elements or reuse the code for a future project. As always, there's pros and cons to both approaches and I'll leave the final choice with you.

Next, add the following CSS to the 'Layout' section of the stylesheet:

.callout {padding:20px 0;}

Step 11: Markup the Services Section

In the services section of the site we want three side-by-side panels that will stack on top of one another on small viewports.

First, let's start with the general markup.

Under the 'Services' section in your index.html, add in the following markup:

<div class="full-width color-two"> 
    <div class="row"> 
        <div class="eight columns centered"> 
        <h2>Our Services</h2> 
        </div> 
    </div> 
 
    <div class="row"> 
        <div class="four columns service"> 
 
        <!-- Content will go here --> 
 
        </div> <!-- end four columns --> 
 
        <div class="four columns service"> 
 
        <!-- Content will go here --> 
 
        </div> <!-- end four columns --> 
 
        <div class="four columns service"> 
 
        <!-- Content will go here --> 
 
        </div> <!-- end four columns --> 
 
    </div><!-- end row --> 
 
</div><!-- end full-width -->

You'll see that we've created a single .row div wrapped in a .full-width div. In the row, we've created three .four .columns div and added in an additional class of .service to each.

We'll add a little padding to the .service class in the 'Layout' section of the style.css stylesheet:

/* SERVICES AREA */ 
.service {padding-bottom: 30px;}

Step 12: Add Content and Style the Service Panels

For the content of each service panel we'll be including an icon font (downloaded from IcoMoon to add a visual representation of the relevant service, a header, some lorem ipsum text and a 'read more' button:

<!-- SERVICES -->    
<div class="full-width color-two"> 
    <div class="row"> 
        <div class="eight columns centered"> 
            <h2>Our Services</h2> 
        </div> 
    </div> 
 
    <div class="row"> 
        <div class="four columns service"> 
            <!-- data-icon attribute sets the correct icon font. See line #140 style.css --> 
            <h3 class="service-icon"><span aria-hidden="true" data-icon="&amp;#x6e;"></span> Webdesign</h3> 
            <p>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. </p> 
 
            <span><a href="#" class="radius button">Learn More &amp;rarr;</a></span> 
        </div> 
 
        <div class="four columns service"> 
            <h3 class="service-icon"><span aria-hidden="true" data-icon="&amp;#x21;"></span>Copywriting</h3> 
 
            <p>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. </p> 
            <span><a href="#" class="radius button">Learn More &amp;rarr;</a></span>     
        </div> 
 
        <div class="four columns service"> 
            <h3 class="service-icon"><span aria-hidden="true" data-icon="&amp;#x22;"></span>Marketing</h3> 
            <p>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. </p> 
            <span><a href="#" class="radius button">Learn More &amp;rarr;</a></span> 
        </div> 
    </div><!-- end row --> 
</div><!-- end full-width -->

You'll note that we are using the data-icon selector along with the relevant unicode for each heading to include the icon in our page. I don't want us to lose momentum, so I won't go into this in much detail. Having said that, if you want to read more about why data-icon is a preferred method for this application, Chris Coyier has a good overview of HTML for Icon Font Usage over on CSS Tricks.

For your reference, the unicode pairings for our icon font are as follows:

  • &#x6e = Screen Icon
  • &#x21 = Pencil Icon
  • &#x22 = Graph Icon

Next, we will style the <h3> element, hookup the IcoMoon <@font-face> and style the icons.

In the 'Typography' section of your stylesheet, add in the following code:

@font-face { 
    font-family: 'IcoMoon'; 
    src: url('../fonts/IcoMoon.eot'); 
    src: url('../fonts/IcoMoon.eot?#iefix') format('embedded-opentype'), 
        url('../fonts/IcoMoon.svg#IcoMoon') format('svg'), 
        url('../fonts/IcoMoon.woff') format('woff'), 
        url('../fonts/IcoMoon.ttf') format('truetype'); 
    font-weight: normal; 
    font-style: normal; 
}

In this code block, we are referencing the IcoMoon fontface with preferred formats for the various browsers.

Next, in the 'Layout' section of the stylesheet, add the following code:

/* Use Data-icon in the HTML to use the icon font */ 
[data-icon]:before { 
    /* providing a fallback bg color for browsers that don't support rgba*/ 
    background-color:#000000;  
    background-color: rgba(0,0,0,.4); 
    /* Sets the background disc and shadow */ 
    box-shadow: 0 1px 1px rgba(255,255,255,0.3), 0 1px 0 rgba(0, 0, 0, 0.33) inset; 
    border-radius: 60px; 
    /* inserts the icon font as pseudo-content */ 
    content: attr(data-icon); 
    display: block; 
    font-family: 'IcoMoon'; 
 
    /* We want the icons to be fixed size (like an image), so we use px instead of em */ 
    font-size: 60px; 
    height: 120px; 
 
    /* Centers the icon in the disc */ 
    line-height:120px;  
} 
 
h3.service-icon span { 
    /* give the span width */ 
    display: block;  
    /* centers the icon and its background */ 
    margin: 0 auto;  
    width: 120px;  
    margin-bottom:20px; 
} 
 
.service > span { 
    padding: 20px 0 30px 0;  
    width:100%;  
    display:block;  
    /* Centers the button, since the button fills its parent with 100% width */ 
    text-align:center;  
}

The comments here should be fairly self explanatory, but in essence this block of CSS creates a 60px high white icon centered in the middle of a circular disc with a diameter of 120px. A chained set of box-shadows gives the disc a subtle 'letterpress' effect. We've also defined the height of all elements in pixels (instead of ems) to give us control over users that resize their default text size in their browsers.

The span that wraps the button is set to width: 100%; and text-align: center; to ensure that the button aligns itself to the horizontal center of the service column.

Great! We're making excellent progress. Let's move on to the featured project section of the site.


Step 13: Markup the Featured Project Section

In this section of the site, we're aiming to add an image of a featured project that is aligned to the center of the page. When we scale down the browser size, we also want this image to respond to the new viewport width and automatically scale down to an appropriate size.

The markup for this section of the site is fairly straight forward:

<!-- FEATURED PROJECT --> 
<div class="full-width color-one"> 
    <div class ="row featured"> 
        <div class="twelve columns"> 
            <h2>Featured Project</h2> 
            <a href="#" class="featured"><img src="images/site_assets/featured_project.png" alt="Featured Project Screenshot"></a> 
        </div> 
    </div>  
</div> <!-- end full-width -->

Styling our featured project is nice and easy, too.

Under the 'Layout' section in your stylesheet, add the following code:

/* Featured Project */ 
.featured { 
    padding-bottom: 30px; 
} 
 
.featured img { 
    /* centers the image to the middle of the .columns div */ 
    position: relative; 
    left: 50%; 
    margin-left:-300px; 
    border: none; 
}

The way that we've positioned the image is worth talking about briefly. Since we know that the width of the image is 600px, we can accurately center the image to its parent by adding position:relative, setting the left position to 50% and then giving it a negative left margin of 300px (half the width of the image).


Step 14: Markup The Contact Section

Creating forms for any website is never a fun job, but luckily for us, Foundation makes the job about as painless as possible. Not only can we use and build upon the default styling from the foundation.css stylesheet (which is quite nice in itself), we can also use rows and columns to control the widths of our input and text area fields.

Let's add in the following code underneath the featured image section of our page and then we'll discuss the way that we have controlled the layout of the form:

<div class="full-width"> 
    <div class="row"> 
        <div class="ten columns centered"> 
            <h2>Get In Contact</h2> 
            
We'd love to hear from you about your next project. Fill in the form below and we'll be in touch with you as soon as we can.
          
            <form> 
                <div class="row"> 
                    <div class="six columns"> <!-- this controls the width of the inputs --> 
                        <label>Name</label> 
                            <input type="text" class="oversize" /> 
                            <label>Email</label> 
                            <input type="text" class="oversize" /> 
                        </div> 
                    </div> 
 
                    <div class="row"> 
                        <div class="twelve columns"> <!-- this controls the width of the textarea --> 
                            <label>Tell Us About Your Project</label> 
                            <textarea></textarea> 
                            <a href="#" class="button" id="submit">Submit</a> 
                        </div> 
                    </div> 
                </form>              
            </div> 
        </div> <!-- end row --> 
</div><!-- end full width -->

The first thing that you will notice is that we have taken advantage of the .centered class to align the ten columns div to the center of the row. Doing this will ensure that the form remains neat and the input elements do not stretch too wide.

Next, you'll see that we have nested a row and a six-column div inside the form to control the width of the input fields. Remember, that because our columns are all measured in percentage widths, the width of a nested column is relative to its parent (in this case the .ten .columns div), and not the 1024px that we have set for all <div class="row"> elements. In other words, a .six .columns div will always be half the width of its parent.

Next, we have closed the row housing the .six .columns div and created a new row that has a child div with classes of .twelve .columns that give the textarea a width of 100% of its parent (which is still the ten column div).

As I mentioned before, the default styles of the Foundation forms are perfectly acceptable as they are, but with that said, we'll tweak a few of the styles so that they fit will with our overall design.

Under the 'Forms' section of your stylesheet, add in the following CSS:

label { 
    font-family: 'Open Sans', sans-serif; 
    font-size:1.3em; 
    color:white; 
    font-weight: 300; 
    padding: 15px 0 5px 0; 
} 
 
input[type="text"], textarea { 
    border-radius:5px; 
    background-color:#110E0C; 
    border:1px solid #0A0807; 
    box-shadow: 0 2px 7px rgba(0, 0, 0, .5) inset; 
    height: 45px; 
    color:white;         
} 
 
input[type="text"]:focus, textarea:focus { 
    /* change the font color on focus */ 
    color:black; 
} 
 
textarea { 
    min-height:200px; 
    font-family: sans-serif; 
    font-size: 18px; 
    overflow-y: hidden; 
}

Step 15: Create the Footer

The final step for our basic page is to add a (very) simple footer.

Add in the following code underneath the 'Footer' section of the index.html file:

<!-- FOOTER --> 
<footer class=" color-four site-footer row" role="contentinfo"> 
        <div class="twelve columns"> 
        <p>Chris Brown for Webdesign Tuts+ Using Zurb Foundation 3.0 &amp;amp; based on code from Jason Weaver and Luke Wroblewski</p> 
        </div>   
</footer>

Also add in the following CSS to the 'Layout' section of your style.css stylesheet:

.site-footer {text-align: center; padding: 40px 0} 
.site-footer p {font-size: 1.2em;}

Step 16: Hook Everything up with Off-Canvas

You've done really well to get this far. Take a break and give yourself a well deserved pat on the back. Just don't rest for too long... the exciting stuff is still to come.

Our next step is to hookup our markup into the off-canvas syntax to achieve the desired effects at small viewport sizes.

Let's just step back for a moment and review what we want to happen when the page is accessed on small viewports:

  1. The main navigation will become hidden, and when the 'Menu' button is pressed a navigation menu will slide into view from the top of the page.
  2. When the 'Contact Us' button is pressed, the main content will slide to the right, being 'pushed' out of the way by the contact form.

We'll add these functions to our HTML, style the elements as required and then return to take a peek under the hood and learn how the off-canvas layout do their magic.

Let's start by setting up the page for off-canvas.


Step 17: Add an Additional Class to the Body to Call Off-Canvas

As our very first baby step, add a class of "off-canvas" to the <body> tag of your index.html:

<body id="page" class="off-canvas">

Next, we'll set up our slide-navigation for small viewports.


Step 18: Small Viewport Navigation Menu

To include a small viewport navigation menu, we'll need to replicate our main navigation.

Return towards the top of your index.html file and add in the following code between the <div class="bpdy"> tag and the <div class="first full-width color-three"> tag:

<!-- SMALL SCREEN NAVIGATION --> 
<nav id="topMenu" role="navigation"> 
    <ul id="nav" class="nav-bar"> 
        <li><a href="" class="main">Home</a></li> 
        <li><a href="" class="main">About</a></li> 
        <li><a href="" class="main">Services</a></li> 
        <li><a href="" class="main">Blog</a></li> 
        <li><a href="" class="main">Contact</a></li>                             
    </ul>                                            
</nav>

The most important thing to note here is the <nav> element. You'll see that we've given it an id of "topMenu" which will trigger the menu when the menu button is pressed and we've also assigned a role="navigation" to the element. It's the latter that the offcanvas.css stylesheet will pickup and apply the result.

It's important to note that we've essentially repeated ourselves here by duplicating our main navigation menu. Not only have we repeated code that goes against the principles of DRY (don't repeat yourself), it also means that if we want to change the navigation menu in any way (e.g. add extra items or include a drop-down menu), we'd need to also change the small viewport navigation menu too... not a great solution for a dynamic site.

A better solution would be to use the jQuery clone() element and append it to the small viewport menu, something along the lines of:

var $clonenav = $('#mainNav').clone(); 
 
$("#topMenu").append($clonenav);

Check out the codepen to see this solution in action.

With all that said, to keep things simple, we'll acknowledge the problems with the duplicate menu solution and run with it for the sake of simplicity.

Next, let's add a little styling to our newly created small viewport navigation menu.

In the 'Media Queries' section of your style.css stylesheet, add in the following:

@media only screen and (max-width: 767px) { 
 
    .nav-bar > li:hover { 
        border-bottom: none; 
    } 
 
    .nav-bar > li > a.main { 
        border:none; 
    } 
 
    .menu-button { 
        /* Add a margin betwen the logo and the 'Menu' button */ 
        margin-top:30px;} 
} /* end media query */

In this small piece of CSS, we've added instructions for the browser to remove the borders for the <li> and a.main elements on viewports 767px and smaller.

If you've followed along closely, you'll be able to see the small viewport navigation menu in action. Save your changes, hop over to your browser, refresh the page and resize the window to a small size. When the 'Menu' button is pressed, you should see our new navigation menu slide into view.


Step 19: Send the 'Contact Us' Section Off-Canvas

The next step is to alter our markup to let offcanvas.css and offcanvas.js know that we want to send the contact form section of the site off-canvas and slide it into view when only the 'Contact Us' button is pressed on small viewports.

To do this, we'll need to wrap our markup in two separate <section> elements and assign roles to these elements.

Return to your index.html file and wrap the markup in section elements like so:

        <section role="main"> <!-- Main Section For OffCanvas --> 
 
            <!-- CALLOUT TEXT 
                ... 
                ... 
                    --> 
 
 
            <!-- SERVICES  
                ... 
                ... 
                    --> 
 
 
            <!-- FEATURED PROJECT 
                ... 
                ... 
                    --> 
 
        </section> <!-- end of main section --> 
 
        <section id="contact" role="complementary"> <!-- This tells the javascript to take this content out of the main page and into the sidebar on small screens --> 
 
            <!-- CONTACT US  
                ... 
                ... 
                    --> 
 
        </section> <!-- end off-canvas sidebar -->

Just in case that isn't clear, you'll want to start the <section role="main"> directly under the <header> and close it directly under the 'Featured Project' code. Next, you'll want to wrap all of the 'Contact Us' code in the <section id="contact" role="complementary"> element. The site footer continues as normal underneath the closing <section>.

Next, we'll need to override some of the offcanvas.css base styles to ensure that our layout doesn't break with our new <section> elements.

In your style.css stylesheet under 'Off Canvas', add in the following code:

 
[role="complementary"], [role="main"] { 
    /* remove the default padding */ 
    padding:0; 
} 
 
@media all and (min-width: 768px) {  
 
  .js [role="complementary"] {  
    /* Sets both the complementary and main sections at 100% width instead of main content / sidebar layout */ 
    width: 100%; 
}  
  .js [role="main"] {  
    width: 100%; padding: 0 0;  
}  
} /* end media query */ 
 
[role="main"]:before { 
    content:""; 
    /* Changes the bg color of the flyout panel */ 
    background-color: #322820; 
}

The most important thing to note here is the setting of the .js [role="complementary"] and .js [role="main"] widths to 100%. In the default styling of the off-canvas layout, these elements are set to a main content / sidebar layout. Changing the widths to 100% ensures that the linear layout that we've created is maintained.

With those changes, we are now very close to completing our project. At this stage, you can resize your browser down to a small size, click the 'Menu' and 'Contact Us' buttons and see all of the off-canvas functionality in action.

All that remains at this stage is to tidy up some loose ends and style some of our elements for small viewports.


Step 20: Style the Page for Small Device Widths

As it is, the page is perfectly acceptable in terms of design, but a few elements of the site need a little polishing for small viewports.

In your style.css stylesheet, add the following CSS to the 'Media Queries' section, before the closing curly bracket of the media query that we've already created. I've included all of our media query in the following code block, but remember that we've already created the first three selectors in Step 15:

@media only screen and (max-width: 767px) { 
 
    .nav-bar > li:hover { 
        border-bottom: none;} 
 
    .nav-bar > li > a.main { 
        border:none;} 
 
    .menu-button { 
        /* Add a margin betwen the logo and the 'Menu' button */ 
        margin-top:30px;} 
 
    .first { 
        padding-bottom:0 !important; 
        border-bottom: none;} 
 
    .full-width {padding-bottom: 10px;} 
 
    .service { 
        /* add a 1px bottom border between the service panels */ 
        padding: 15px 15px 30px 15px;  
        border-bottom: 1px solid rgba(0,0,0,.2);} 
 
    .service:last-child { 
        /* Removes the bottom border on the last service panel */  
        border:none;} 
 
    /* ensures that the featured project div fills 100% of its parent */ 
    .featured {width:100%;} 
 
    /* Removes the centering of the featured image and resizes the image as the viewport is scaled down */ 
    .featured img {width:100%; left:0; margin-left:0;} 
 
} /* end media query */

And with that, we've finished! Great work!


Step 21: Looking Under the Hood

I'm sure that by now you are looking forward to a coffee (or perhaps something stronger!) and a well deserved break.

I won't be going through each line of code with you, but I did want to take this opportunity to take a quick look behind the scenes at the off-canvas code to show you in simple terms how we've achieved what we've achieved today.

To start off with, as I'm sure that you've already picked up, the most important hooks in our code are the role attributes given to each of the two <section> elements in our markup. While the use of roles is not the only way to accomplish the off-canvas effect, they do add an extra layer of elegance and accessibility to the code.

Accessible Rich Internet Application (ARIA) roles are a small part of the Web Accessibility Initiative and allow website developers to add additional information to elements that can add extra context for visitors to the site that are using screen readers. While the list of available roles is extensive, we've used the two navigation roles of 'main' and 'complementary', which when you think of it is quite appropriate for our purposes today. While it's a slow read, you can read more about roles from the W3C.

In terms of functionality, the first thing that the off-canvas layout does is to position the small viewport navigation menu off of screen on large viewport sizes with the following javascript:

// jquery.offcanvas.js line 1-5 
// Set the negative margin on the top menu for slide-menu pages 
  var $selector = $('#topMenu'); 
  if ($selector.length > 0) { 
    $selector.css("margin-top", $selector.height() * -1); 
  }

And with the CSS, the default display type is set to display: none; on wide viewports:

/* offcanvas.css line 46 */ 
@media all and (min-width: 768px) { .js menu-button, .js .sidebar-button { display: none; }

Next, the jquery.offcanvas.js javascript applies a class of 'active' to the body element when either of the small viewport panels is selected:

//jquery.offcanvas.js lines 7-23 
 
// Watch for clicks to show the sidebar 
  $selector = $('#sidebarButton'); 
  if ($selector.length > 0) { 
    $('#sidebarButton').click(function(e){ 
      e.preventDefault(); 
      $('body').toggleClass('active'); 
    }); 
  } 
 
  // Watch for clicks to show the menu for slide-menu pages 
  $selector = $('#menuButton'); 
  if ($selector.length > 0)  { 
    $('#menuButton').click(function(e){ 
      e.preventDefault(); 
      $('body').toggleClass('active-menu'); 
    }); 
  }

When the 'active' class is applied to the body, the offcanvas.css stylesheet repositions the section with role=[main] 80% to the right and sets the role=[complementary] section to a margin: 0;:

/* offcanvas.css lines 40-42 */ 
.active [role="complementary"] { margin-left: 0; } 
 
.active [role="main"] { margin-right: -80%; }

This is a pretty simplistic view of the workings of off-canvas, but serves to give you a high-level overview of how the layout works. I highly recommend digging into offcanvas.css and jquery.offcanvas.js to bring yourself up to speed with the intricacies of the code.


Conclusion and Review

If you've followed along to this point, congratulations! Today we've jumped straight into the the deep end with Foundation and off-canvas to produce a functional, practical home page layout that has real-world applications that is bound to impress your next client.

This is only one of the off-canvas configurations that we could have used today. In fact, in the offcanvas downloads are three additional layouts for you to play with. Just open up the .html files and insert your own code to experiment and customize your own off-canvas pages.

If you have any questions, please leave them in the comments and I'll try my best to answer them for you.

Did you enjoy working with Foundation? Would you like to see more tutorials in the future exploring this framework? If so, please let us know!


Changelog: 22 October 2012

Since the publication of this tutorial Foundation has altered in a few subtle ways. Other best practices in web design have also emerged, so I've updated the tutorial to reflect these changes.

  • edited instructions within step 6 re: containers in foundation 3.0
  • removed <div class="container"> tags, rules and references throughout the tutorial, index.html and style.css files
  • changed the hidden h1 method from position: absolute; left:-9999px to font:0/0 a; etc.
  • removed extra <div class="row"> x2 from step 11
  • changed the footer to include links

Advertisement
Related Posts