Home Web Development HTML5 and CSS3: Building Responsive Websites

HTML5 and CSS3: Building Responsive Websites

By Ben Frain , Thoriq Firdaus , Benjamin LaGrone
books-svg-icon Book
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
Responsive web design is an explosive area of growth in modern web development due to the huge volume of different device sizes and resolutions that are now commercially available. The Internet is going mobile. Desktop-only websites just aren’t good enough anymore. With mobile internet usage still rising and tablets changing internet consumption habits, you need to know how to build websites that will just “work,” regardless of the devices used to access them. This Learning Path course explains all the key approaches necessary to create and maintain a modern responsive design using HTML5 and CSS3. Our first module is a step-by-step introduction to ease you into the responsive world, where you will learn to build engaging websites. With coverage of Responsive Grid System, Bootstrap, and Foundation, you will discover three of the most robust frameworks in responsive web design. Next, you’ll learn to create a cool blog page, a beautiful portfolio site, and a crisp professional business site and make them all totally responsive. Packed with examples and a thorough explanation of modern techniques and syntax, the second module provides a comprehensive resource for all things “responsive.” You’ll explore the most up-to-date techniques and tools needed to build great responsive designs, ensuring that your projects won’t just be built “right” for today, but in the future too. The last and the final module is your guide to obtaining full access to next generation devices and browser technology. Create responsive applications that make snappy connections for mobile browsers and give your website the latest design and development advantages to reach mobile devices. At the end of this course, you will learn to get and use all the tools you need to build and test your responsive web project performance and take your website to the next level. This Learning Path combines some of the best that Packt has to offer in one complete, curated package. It includes content from the following Packt products: ?Responsive Web Design by Example: Beginner’s Guide - Second Edition by Thoriq Firdaus ?Responsive Web Design with HTML5 and CSS3 - Second Edition by Ben Frain ?HTML5 and CSS3 Responsive Web Design Cookbook by Benjamin LaGrone
Publication date:
October 2016
Publisher
Packt
ISBN
9781787124813

   

I still remember, back when I was a kid, a mobile phone came with a mere tiny size monochromatic screen. All we could do at that time was make a phone call, text, and play a simple game. Today, mobile devices have drastically advanced in many ways.

New mobile devices are built with varying screen sizes; some even come with higher DPI or resolution. Most new mobile devices are now equipped with a touch-enabled screen, allowing us to interact with the device conveniently using a tap or a swipe of fingers. The screen orientation is switchable between portrait and landscape. The software is also more capable compared to older devices. The mobile browser, in particular, is now able to render and display web pages that are as good as a browser in a desktop computer.

In addition, the number of mobile users has exploded in the last couple of years. We can now see many people around spending countless hours facing their mobile devices, a phone, or a tablet, doing things such as running their businesses on the go or simple Internet browsing. The number of mobile users is likely to grow in the years to come and may even outnumber the total number of desktop users.

That is to say, mobiles have changed the Web and changed the way people use the Internet and enjoy websites. These advancements in mobile devices and the increasing mobile Internet usage prompts questions on a new paradigm to build websites that are accessible and function well in varying circumstances. This is where Responsive Web Design comes in.

In this chapter, we will cover the following topics:

Responsive web design is one of the most discussed topics in the web design and development community. So, I believe many of you have heard about it to a certain extent.

Ethan Marcotte was the one who coined the term "responsive web design". He suggests in his article Responsive Web Design (http://alistapart.com/article/responsive-web-design/), that the Web should seamlessly adjust and adapt to the environment where the users view the website rather than addressing it exclusively for a specific platform. In other words, the website should be responsive, it should be presentable on any screen size, regardless of the platform on which it is viewed.

Take the Time website (http://time.com/) as an example. The web page fits nicely on a desktop browser with a large screen size and also on a mobile browser with a limited viewable area. The layout shifts and adapts as the viewport size changes. As you can see in the following screenshot, on the mobile browser, the background color of the header is dark grey, the image is scaled down proportionally, and the Tap bar appears where Time hides the latest news, magazine, and videos sections:

Responsive web design in a nutshell

There are two components to build responsive websites, namely, viewport meta tag and media queries.

Before smartphones, such as the iPhone, became mainstream, every website was built to be around 1000 px in width or 980 px wide and it was zoomed out to fit into the mobile phone screen, which eventually made the website unreadable. Hence, the <meta name="viewport"> was created.

In a nutshell, the viewport meta tag is used to define the web page scale and its visible area (viewport) in the browser. The following code is an example of a viewport meta tag in action:

The preceding viewport meta tag specification defines the web page viewport width to follow the device. It also defines the web page scale upon opening the web page for the first time at 1:1, in a way that the sizes and the dimensions of the web page content should be persistent; they should not be scaled up or scaled down.

In favor of comprehending how the viewport meta tag would affect a web page layout, I have created two web pages for comparison; one with the viewport meta tag added in and the other one without it. You can see the difference in the following screenshot:

Viewport meta tag

The first website shown in the preceding image is issued with the viewport meta tag using the exact same specification as in our previous code example. As we have specified width=device-width, the browser acknowledges that the website viewport is at the same size as the device screen, so that it will not squish the web page to fit in the entire screen. The initial-scale=1 will retain the title and the paragraph in their original size.

In the second website's example, as we did not add the viewport meta tag, the browser assumed that the web page should be displayed entirely. So, the browser forced the whole website down to fit within the whole screen area, making the title and the text totally unreadable.

Building a responsive website can be very tedious work. There are many measurements to be considered while building a responsive website, one of which would be creating the responsive grid.

The grid helps us build websites with proper alignment. If you have ever used 960.gs (http://960.gs/), which is one of the popular CSS frameworks, you would have experienced how easy it is to organize the web page layout by adding preset classes, such as grid_1 or push_1, in the elements.

However, the 960.gs grid is set in a fixed unit, namely, pixel (px), which is not applicable when it comes to building a responsive website. We need a framework with the grid set in percentage (%) unit to build responsive websites; we need a responsive framework.

A responsive framework provides the building blocks to build responsive websites. Generally, it includes the classes to assemble a responsive grid, the basic styles for typography and form inputs, and a few styles to address various browser quirks. Some frameworks even go further with a series of styles to create common design patterns and web user interfaces such as buttons, navigation bars, and image slider. These predefined styles allow us to develop responsive websites faster with less hassle. The following are a few other reasons why using a responsive framework is a favorable option to build responsive websites:

Through the course of this module, we will be building three responsive websites by using three different responsive frameworks, namely Responsive.gs, Bootstrap, and Foundation.

Responsive.gs (http://responsive.gs/) is a lightweight, responsive framework, which is merely 1 KB in size when compressed. Responsive.gs is based on a width of 940 px, and made in three variants of grids, that is, 12, 16, and 24 columns. What's more, Responsive.gs is shipped with box-sizing polyfill, which enables CSS3 box-sizing in Internet Explorer 6, 7, and 8, and makes it decently presentable in those browsers.

Bootstrap (http://getbootstrap.com/) was originally built by Mark Otto (http://markdotto.com/) and initially intended only for internal use on Twitter. In short, Bootstrap was then launched for free for public consumption.

If you refer to the initial development, the responsive feature was not yet added. It was then added in Version 2 due to the increasing demand for creating responsive websites.

Bootstrap also comes with many more added features as compared to Responsive.gs. It is packed with preset user interface styles, which comprise common user interfaces used on websites such as buttons, navigation bars, pagination, and forms, so you don't have to create them from scratch again when starting a new project. On top of that, Bootstrap is also powered with some custom jQuery plugins such as image slider, carousel, popover, and modal box.

You can use and customize Bootstrap in many ways. You can directly customize the Bootstrap theme and its components directly through the CSS style sheets, the Bootstrap customize and download page (http://getbootstrap.com/customize/), or the Bootstrap LESS variables and mixins, which are used to generate the style sheets.

In this module, we will go into Bootstrap in Chapter 5, Developing a Portfolio Website with Bootstrap, and Chapter 6, Polishing the Responsive Portfolio Website with LESS, to build a responsive portfolio website.

Foundation (http://foundation.zurb.com/) is a framework created by ZURB, a design agency based in California. Similar to Bootstrap, Foundation is not just a responsive CSS framework; it is shipped with a preset grid, components, and a number of jQuery plugins to present interactive features.

Some high-profile brands, such as McAfee (http://www.mcafee.com/common/privacy/english/slide.html), which is one of the most respectable brands for computer antivirus, have built their websites using Foundation.

The Foundation style sheet is powered by Sass, a Ruby-based CSS preprocessor. We will be discussing more about Sass, along with the Foundation features in the last two chapters of this module; therein, we will be developing a responsive website for a startup company.

Our discussion on responsive web design here, though essential, is merely the tip of the iceberg. There is so much more about responsive web design than what we have recently covered in the preceding sections. I would suggest that you take your time to get yourself more insight and remove any apprehension on responsive web design, including the concept, the technicalities, and some constraints.

The following are some of the best recommendations for references:

The Responsive.gs framework

Responsive.gs (

http://responsive.gs/) is a lightweight, responsive framework, which is merely 1 KB in size when compressed. Responsive.gs is based on a width of 940 px, and made in three variants of grids, that is, 12, 16, and 24 columns. What's more, Responsive.gs is shipped with box-sizing polyfill, which enables CSS3 box-sizing in Internet Explorer 6, 7, and 8, and makes it decently presentable in those browsers.

Bootstrap (http://getbootstrap.com/) was originally built by Mark Otto (http://markdotto.com/) and initially intended only for internal use on Twitter. In short, Bootstrap was then launched for free for public consumption.

If you refer to the initial development, the responsive feature was not yet added. It was then added in Version 2 due to the increasing demand for creating responsive websites.

Bootstrap also comes with many more added features as compared to Responsive.gs. It is packed with preset user interface styles, which comprise common user interfaces used on websites such as buttons, navigation bars, pagination, and forms, so you don't have to create them from scratch again when starting a new project. On top of that, Bootstrap is also powered with some custom jQuery plugins such as image slider, carousel, popover, and modal box.

You can use and customize Bootstrap in many ways. You can directly customize the Bootstrap theme and its components directly through the CSS style sheets, the Bootstrap customize and download page (http://getbootstrap.com/customize/), or the Bootstrap LESS variables and mixins, which are used to generate the style sheets.

In this module, we will go into Bootstrap in Chapter 5, Developing a Portfolio Website with Bootstrap, and Chapter 6, Polishing the Responsive Portfolio Website with LESS, to build a responsive portfolio website.

Foundation (http://foundation.zurb.com/) is a framework created by ZURB, a design agency based in California. Similar to Bootstrap, Foundation is not just a responsive CSS framework; it is shipped with a preset grid, components, and a number of jQuery plugins to present interactive features.

Some high-profile brands, such as McAfee (http://www.mcafee.com/common/privacy/english/slide.html), which is one of the most respectable brands for computer antivirus, have built their websites using Foundation.

The Foundation style sheet is powered by Sass, a Ruby-based CSS preprocessor. We will be discussing more about Sass, along with the Foundation features in the last two chapters of this module; therein, we will be developing a responsive website for a startup company.

Our discussion on responsive web design here, though essential, is merely the tip of the iceberg. There is so much more about responsive web design than what we have recently covered in the preceding sections. I would suggest that you take your time to get yourself more insight and remove any apprehension on responsive web design, including the concept, the technicalities, and some constraints.

The following are some of the best recommendations for references:

A word on CSS box model

HTML elements, which are categorized as block-level elements, are essentially boxes drawn with the content width, height, margin, padding, and border through CSS. Prior to CSS3, we were facing

Bootstrap (http://getbootstrap.com/) was originally built by Mark Otto (http://markdotto.com/) and initially intended only for internal use on Twitter. In short, Bootstrap was then launched for free for public consumption.

If you refer to the initial development, the responsive feature was not yet added. It was then added in Version 2 due to the increasing demand for creating responsive websites.

Bootstrap also comes with many more added features as compared to Responsive.gs. It is packed with preset user interface styles, which comprise common user interfaces used on websites such as buttons, navigation bars, pagination, and forms, so you don't have to create them from scratch again when starting a new project. On top of that, Bootstrap is also powered with some custom jQuery plugins such as image slider, carousel, popover, and modal box.

You can use and customize Bootstrap in many ways. You can directly customize the Bootstrap theme and its components directly through the CSS style sheets, the Bootstrap customize and download page (http://getbootstrap.com/customize/), or the Bootstrap LESS variables and mixins, which are used to generate the style sheets.

In this module, we will go into Bootstrap in Chapter 5, Developing a Portfolio Website with Bootstrap, and Chapter 6, Polishing the Responsive Portfolio Website with LESS, to build a responsive portfolio website.

Foundation (http://foundation.zurb.com/) is a framework created by ZURB, a design agency based in California. Similar to Bootstrap, Foundation is not just a responsive CSS framework; it is shipped with a preset grid, components, and a number of jQuery plugins to present interactive features.

Some high-profile brands, such as McAfee (http://www.mcafee.com/common/privacy/english/slide.html), which is one of the most respectable brands for computer antivirus, have built their websites using Foundation.

The Foundation style sheet is powered by Sass, a Ruby-based CSS preprocessor. We will be discussing more about Sass, along with the Foundation features in the last two chapters of this module; therein, we will be developing a responsive website for a startup company.

Our discussion on responsive web design here, though essential, is merely the tip of the iceberg. There is so much more about responsive web design than what we have recently covered in the preceding sections. I would suggest that you take your time to get yourself more insight and remove any apprehension on responsive web design, including the concept, the technicalities, and some constraints.

The following are some of the best recommendations for references:

CSS3 box sizing

CSS3 introduced a new

Bootstrap (http://getbootstrap.com/) was originally built by Mark Otto (http://markdotto.com/) and initially intended only for internal use on Twitter. In short, Bootstrap was then launched for free for public consumption.

If you refer to the initial development, the responsive feature was not yet added. It was then added in Version 2 due to the increasing demand for creating responsive websites.

Bootstrap also comes with many more added features as compared to Responsive.gs. It is packed with preset user interface styles, which comprise common user interfaces used on websites such as buttons, navigation bars, pagination, and forms, so you don't have to create them from scratch again when starting a new project. On top of that, Bootstrap is also powered with some custom jQuery plugins such as image slider, carousel, popover, and modal box.

You can use and customize Bootstrap in many ways. You can directly customize the Bootstrap theme and its components directly through the CSS style sheets, the Bootstrap customize and download page (http://getbootstrap.com/customize/), or the Bootstrap LESS variables and mixins, which are used to generate the style sheets.

In this module, we will go into Bootstrap in Chapter 5, Developing a Portfolio Website with Bootstrap, and Chapter 6, Polishing the Responsive Portfolio Website with LESS, to build a responsive portfolio website.

Foundation (http://foundation.zurb.com/) is a framework created by ZURB, a design agency based in California. Similar to Bootstrap, Foundation is not just a responsive CSS framework; it is shipped with a preset grid, components, and a number of jQuery plugins to present interactive features.

Some high-profile brands, such as McAfee (http://www.mcafee.com/common/privacy/english/slide.html), which is one of the most respectable brands for computer antivirus, have built their websites using Foundation.

The Foundation style sheet is powered by Sass, a Ruby-based CSS preprocessor. We will be discussing more about Sass, along with the Foundation features in the last two chapters of this module; therein, we will be developing a responsive website for a startup company.

Our discussion on responsive web design here, though essential, is merely the tip of the iceberg. There is so much more about responsive web design than what we have recently covered in the preceding sections. I would suggest that you take your time to get yourself more insight and remove any apprehension on responsive web design, including the concept, the technicalities, and some constraints.

The following are some of the best recommendations for references:

The Bootstrap framework

Bootstrap (

http://getbootstrap.com/) was originally built by Mark Otto (http://markdotto.com/) and initially intended only for internal use on Twitter. In short, Bootstrap was then launched for free for public consumption.

If you refer to the initial development, the responsive feature was not yet added. It was then added in Version 2 due to the increasing demand for creating responsive websites.

Bootstrap also comes with many more added features as compared to Responsive.gs. It is packed with preset user interface styles, which comprise common user interfaces used on websites such as buttons, navigation bars, pagination, and forms, so you don't have to create them from scratch again when starting a new project. On top of that, Bootstrap is also powered with some custom jQuery plugins such as image slider, carousel, popover, and modal box.

You can use and customize Bootstrap in many ways. You can directly customize the Bootstrap theme and its components directly through the CSS style sheets, the Bootstrap customize and download page (http://getbootstrap.com/customize/), or the Bootstrap LESS variables and mixins, which are used to generate the style sheets.

In this module, we will go into Bootstrap in Chapter 5, Developing a Portfolio Website with Bootstrap, and Chapter 6, Polishing the Responsive Portfolio Website with LESS, to build a responsive portfolio website.

Foundation (http://foundation.zurb.com/) is a framework created by ZURB, a design agency based in California. Similar to Bootstrap, Foundation is not just a responsive CSS framework; it is shipped with a preset grid, components, and a number of jQuery plugins to present interactive features.

Some high-profile brands, such as McAfee (http://www.mcafee.com/common/privacy/english/slide.html), which is one of the most respectable brands for computer antivirus, have built their websites using Foundation.

The Foundation style sheet is powered by Sass, a Ruby-based CSS preprocessor. We will be discussing more about Sass, along with the Foundation features in the last two chapters of this module; therein, we will be developing a responsive website for a startup company.

Our discussion on responsive web design here, though essential, is merely the tip of the iceberg. There is so much more about responsive web design than what we have recently covered in the preceding sections. I would suggest that you take your time to get yourself more insight and remove any apprehension on responsive web design, including the concept, the technicalities, and some constraints.

The following are some of the best recommendations for references:

The Foundation framework

Foundation (

http://foundation.zurb.com/) is a framework created by ZURB, a design agency based in California. Similar to Bootstrap, Foundation is not just a responsive CSS framework; it is shipped with a preset grid, components, and a number of jQuery plugins to present interactive features.

Some high-profile brands, such as McAfee (http://www.mcafee.com/common/privacy/english/slide.html), which is one of the most respectable brands for computer antivirus, have built their websites using Foundation.

The Foundation style sheet is powered by Sass, a Ruby-based CSS preprocessor. We will be discussing more about Sass, along with the Foundation features in the last two chapters of this module; therein, we will be developing a responsive website for a startup company.

Our discussion on responsive web design here, though essential, is merely the tip of the iceberg. There is so much more about responsive web design than what we have recently covered in the preceding sections. I would suggest that you take your time to get yourself more insight and remove any apprehension on responsive web design, including the concept, the technicalities, and some constraints.

The following are some of the best recommendations for references:

A brief introduction to CSS preprocessors

Both Bootstrap

Our discussion on responsive web design here, though essential, is merely the tip of the iceberg. There is so much more about responsive web design than what we have recently covered in the preceding sections. I would suggest that you take your time to get yourself more insight and remove any apprehension on responsive web design, including the concept, the technicalities, and some constraints.

The following are some of the best recommendations for references:

Have a Go Hero — delve into responsive web design

Our discussion on responsive web design here, though essential, is merely the tip of the iceberg. There is so much more about responsive web design than what we have recently covered in the preceding sections. I would suggest that you take your time to get yourself more insight and remove any apprehension on responsive web design, including the concept, the technicalities, and some constraints.

The following are some

of the best recommendations for references:

Pop Quiz — responsive web design main components

Q1. In his article, which we have referred to about two times in this chapter, Ethan Marcotte mentioned the main technical ingredients that formulate a responsive website. What are those main components?

Viewport Meta Tag and CSS3 Media Queries.
Fluid grids, flexible images, and media queries.
Responsive images, breakpoints, and polyfills.

Q2. What is a viewport?

The screen size of the device.
The region where the web page is rendered.
The meta tag to set the web page's viewport size.

Q3. Which one of these is the correct way to declare CSS3 Media Queries?

@media (max-width: 320px) { p{ font-size:11px; }}
@media screen and (max-device-ratio: 320px) { div{ color:white; }}
<link rel="stylesheet" media="(max-width: 320px)" href="core.css" />
 

Every professional has a set of tools that facilitates their work and gets the job done. Likewise, we will also need our own tools to do our bit of building responsive websites. So, before we start working on the projects in this module, the following are the tools we have to prepare.

Tools that we will have to prepare include:

As soon as we start writing code for HTML, CSS, and JavaScript, we need a code editor. A code editor is an indispensible tool to develop websites. Technically, you will only need text editors such as TextEdit in OS X or Notepad in Windows to write and edit code. However, by using a code editor, your eyes will be less irritated.

Similar to Microsoft Word, which has been specially designed to make word and paragraph formatting more intuitive, a code editor is designed with a set of special features that improves code writing experiences such as syntax highlighting, auto-completion, code snippets, multiple line selection, and supporting a large number of languages. Syntax highlighting will display code in different colors, enhancing code readability and make it easy to find errors in the code.

My personal preference for a code editor, and the one that I will use in this module, is Sublime Text (http://www.sublimetext.com/). Sublime Text is a cross-platform code editor available for Windows, OS X, and Linux. It can be downloaded free for evaluation for an unlimited time.

Perform the following steps to install Sublime Text Package Control; this will allow us to install Sublime Text extension easily:

What just happened?

We just installed Package Control to search, install, list, and remove extensions in Sublime Text easily. You can access Package Control through Command Palette…, which can be accessed by navigating to the Tools | Command Palette… menu. Alternatively, you can press a key shortcut to access it faster. Windows and Linux users can press Ctrl + Shift + P, while OS X users can press Command + Shift + P. Then, search for Command Palette… to list all available commands for Package Control.

What just happened? Have a go hero – install the LESS and Sass syntax-highlighting package

As mentioned in the first chapter, we are going to use these CSS preprocessors to compose styles in two Setting up a local server

Having a local server set up and running on our computer is necessary while developing a website. When we use a local

XAMPP is available for Windows, OS X, and Linux. Download the installer from https://www.apachefriends.org/download.html; pick the installer in accordance with the platform you are using right now. Each platform will have a different installer with different extensions; Windows users will get .exe, OSX users will get .dmg, while Linux users will get .run. Perform the following steps to install XAMPP in Windows:

Perform the following steps to install XAMPP in OS X:

Perform the following steps to install XAMPP in Ubuntu:

Ideally, we have to test our responsive websites in as many browsers as possible, including beta browsers such as Firefox Nightly (http://nightly.mozilla.org/) and Chrome Canary (http://www.google.com/intl/en/chrome/browser/canary.html). This is to ensure that our website is functioning well in different environments. However, during the development, we may pick one primary browser for development and as the point of reference of how the website should be put on display.

In this module, we will be using Chrome (https://www.google.com/intl/en/chrome/browser/). It is my humble opinion that Chrome, besides running fast, is also a very powerful web development tool. Chrome comes with a set of tools that are ahead of the other browsers. The following are two of my favorite tools in Chrome when it comes to developing responsive websites.

What just happened?

We have just set up a local server in our computer with MAMP. You can now access the local server with the http://localhost/ address through the browsers. For OS X users, however, the address is your computer username followed by .local. Say that your username is john the local server is accessible through john.local. The local server directory path is

Ideally, we have to test our responsive websites in as many browsers as possible, including beta browsers such as Firefox Nightly (http://nightly.mozilla.org/) and Chrome Canary (http://www.google.com/intl/en/chrome/browser/canary.html). This is to ensure that our website is functioning well in different environments. However, during the development, we may pick one primary browser for development and as the point of reference of how the website should be put on display.

In this module, we will be using Chrome (https://www.google.com/intl/en/chrome/browser/). It is my humble opinion that Chrome, besides running fast, is also a very powerful web development tool. Chrome comes with a set of tools that are ahead of the other browsers. The following are two of my favorite tools in Chrome when it comes to developing responsive websites.

Choosing a CSS preprocessor compiler

As we will be using LESS and Sass to generate the style sheets of our responsive website, we will need a tool that will

Ideally, we have to test our responsive websites in as many browsers as possible, including beta browsers such as Firefox Nightly (http://nightly.mozilla.org/) and Chrome Canary (http://www.google.com/intl/en/chrome/browser/canary.html). This is to ensure that our website is functioning well in different environments. However, during the development, we may pick one primary browser for development and as the point of reference of how the website should be put on display.

In this module, we will be using Chrome (https://www.google.com/intl/en/chrome/browser/). It is my humble opinion that Chrome, besides running fast, is also a very powerful web development tool. Chrome comes with a set of tools that are ahead of the other browsers. The following are two of my favorite tools in Chrome when it comes to developing responsive websites.

Browser for development

Ideally, we have to test our responsive websites in as many browsers as possible, including beta

browsers such as Firefox Nightly (http://nightly.mozilla.org/) and Chrome Canary (http://www.google.com/intl/en/chrome/browser/canary.html). This is to ensure that our website is functioning well in different environments. However, during the development, we may pick one primary browser for development and as the point of reference of how the website should be put on display.

In this module, we will be using Chrome (https://www.google.com/intl/en/chrome/browser/). It is my humble opinion that Chrome, besides running fast, is also a very powerful web development tool. Chrome comes with a set of tools that are ahead of the other browsers. The following are two of my favorite tools in Chrome when it comes to developing responsive websites.

Source maps

One of the
Mobile emulator

There isn't any substitution

Perform the following steps to install Node.js in Windows, OS X, and Ubuntu (Linux). You may skip directly to the section of the platform you are using.

Perform the following steps to install Node.js in Windows:

Perform the following steps to install Node.js in OS X:

Perform the following steps to install Node.js in Ubuntu:

Installing Node.js in Ubuntu is quite straightforward. Node.js can be installed through Ubuntu's Advanced Packaging Tool (APT) or apt-get. If you are using Ubuntu version 13.10 or the latest version, you can launch the terminal and run the following two commands consecutively:

If you are using Ubuntu version 13.04 or earlier, run the following command instead:

What just happened?

We have just installed Node.js and npm command, which enable us to use Bower later on through the Node.js Package Manager (NPM). The npm command line
Have a go hero – get yourself familiar with command lines

Throughout this module, we will be dealing with a number of command lines to install Bower, as well as Bower packages. Yet, if you are

Perform the following steps to install Bower:

What just happened?

We have just installed Bower on the computer, which enables the bower command. The -g parameter that we included in the preceding command installs Bower globally, so that we are able to execute the bower command in any directory in the computer. Bower commands

After installing Bower, we have access to a set of command lines to operate Bower functionalities. We will Pop quiz – web development tools and command lines

Q1. We have just installed Sublime Text along with Package Control. What is the Package Control used for?

To install and remove the Sublime Text package easily.
To install LESS and Sass/SCSS packages.
To manage packages in Sublime Text.

Q2. We have also installed XAMPP. Why did we need to install XAMPP?

To host the websites locally.
To develop websites locally.
To manage the project locally.
 

In the previous chapter, we installed a number of software that will facilitate our projects. Here, we will start off our very first project. In this project, we are going to build a responsive blog.

Having a blog is essential for a company. Even several Fortune 500 companies such as FedEx (http://outofoffice.van.fedex.com/), Microsoft (https://blogs.windows.com/) and General Motors (http://fastlane.gm.com/) have official corporate blogs. A blog is a great channel for the company to publish official news as well as to connect with their customers and the masses. Making the blog responsive is the way to go to make the blog more accessible to the readers who may access the site through a mobile device, such as a phone or tablet.

As the blog that we are going to build in this first project will not be that complex, this chapter would be an ideal chapter for those who have just come across responsive web design.

So let's get started.

To sum up, in this chapter, we will cover the following topics:

As we mentioned in Chapter 1, Responsive Web Design, Responsive.gs is a lightweight CSS framework. It comes only with the bare minimum requirements for building responsive websites. In this section, we are going to see what is included in Responsive.gs.

Responsive.gs is shipped with a series of reusable classes to form the responsive grid that makes it easier and faster for web designers to build web page layout. These classes contain preset style rules that have been carefully calibrated and tested. So we can simply drop in these classes within the HTML element to construct the responsive grid. The following is a list of the classes in Responsive.gs:

Class name

Usage

container

We use this class to set the web page container and align it to the center of the browser window. This class, however, does not give the element width. Responsive.gs gives us the flexibility to set the width as per our requirement.

row, group

We use these two classes to wrap a group of columns. Both of these classes are set with so called self-clearing floats that fix some layout issues caused by the element with the CSS float property.

Check the following references for further information about the CSS float property and the issue it may cause to a web page layout:

col

We use this class to define the column of the web page. This class is set with the CSS float property. So any elements set with this class have to be contained within an element with the row or group class to avoid the issues caused by the CSS float property.

gutters

We use this class to add spaces between the columns set with the preceding col class.

span_{x}

This class defines the column width. So we use this class in tandem with the col class.

Responsive.gs comes in three variants of grid, which gives us flexibility while organizing the web page layout. Responsive.gs is available in the 12-, 16-, and 24-columns format. These variants are set in three separate style sheets. If you download Responsive.gs package and then unpack it, you will find three style sheets named responsive.gs.12col.css, responsive.gs.16col.css, and responsive.gs.24col.css.

The only difference between these style sheets is the number of span_ classes defined within it. It is apparent that the 24-column format style sheet has the most number of span_{x} classes; the class stretches from span_1 to span_24. If you need greater flexibility on dividing your page, then using the 24-column format of Responsive.gs is the way to go. Though each column may be too narrow.

clr

This class is provided to address the floating issue. We use this class in the occasion where using the row class would not be semantically appropriate.

Now, let's see how we apply them in an example to discover how they really work. Many times, you will see that a web page is divided into a multiple columns structure. Take that into account as our example here; we can do the following to construct a web page with two columns of content:

As you can see from the preceding code snippet, we first added container that wraps all the contents. Then, it is followed by div with a row class to wrap the columns. At the same time, we also added the gutters class so that there will be blank space between the two columns. In this example, we used the 12-column format. Therefore, to split the page into two equal columns, we added the span_6 class for each column. This is to say that the number of span_{x} classes should be equal to 12, 16, or 24 in accordance with the variant we are using in order for the columns to cover the entire container. So, if we used the 16-columns format, for example, we may add span_8 instead.

In the browser, we will see the following output:

The classes

Paul Boag, in his article Semantic code: What? Why? How? (http://boagworld.com/dev/semantic-code-what-why-how/) wrote:

HTML was originally intended as a means of describing the content of a document, not as a means to make it appear visually pleasing.

Unlike traditional content outlets such as newspapers or magazines, which are apparently intended for humans, the Web is read both by humans and machines such as search engines and screen readers that help visually impaired people navigate websites. So making our website structure semantic is really encouraged. Semantic markup allows these machines to understand the content better and also makes the content more accessible in different formats.

On that account, HTML5 introduces a bunch of new elements in its mission to make the web more semantic. The following is a list of elements that we are going to use for the blog:

These new HTML elements make our document markup more descriptive and meaningful. Unfortunately, Internet Explorer 6, 7, and 8 will not recognize them. Thus, the selectors and style rules that address these elements are inapplicable; it is as if these new elements are not included in the Internet Explorer dictionary.

This is where a polyfill named HTML5Shiv comes into play. We will include HTML5Shiv (https://github.com/aFarkas/html5shiv) to make Internet Explorer 8 and its lower versions acknowledge these new elements. Read the following post (http://paulirish.com/2011/the-history-of-the-html5-shiv/) by Paul Irish for the history behind HTML5Shiv; how it was invented and developed.

Furthermore, older Internet Explorer versions won't be able to render the content in the HTML5 placeholder attribute. Fortunately, we can patch mimic the placeholder attribute functionality in the old Internet Explorer with a polyfill (https://github.com/UmbraEngineering/Placeholder). We will use it later on the blog as well.

Responsive.gs is also shipped with two polyfills to enable certain features that are not supported in Internet Explorer 6, 7, and 8. From now on, let's refer to these browser versions as "old Internet Explorer", shall we?

HTML5 search input types

Besides the new elements, we will also add one particular new type of input on the blog, search. As the

These new HTML elements make our document markup more descriptive and meaningful. Unfortunately, Internet Explorer 6, 7, and 8 will not recognize them. Thus, the selectors and style rules that address these elements are inapplicable; it is as if these new elements are not included in the Internet Explorer dictionary.

This is where a polyfill named HTML5Shiv comes into play. We will include HTML5Shiv (https://github.com/aFarkas/html5shiv) to make Internet Explorer 8 and its lower versions acknowledge these new elements. Read the following post (http://paulirish.com/2011/the-history-of-the-html5-shiv/) by Paul Irish for the history behind HTML5Shiv; how it was invented and developed.

Furthermore, older Internet Explorer versions won't be able to render the content in the HTML5 placeholder attribute. Fortunately, we can patch mimic the placeholder attribute functionality in the old Internet Explorer with a polyfill (https://github.com/UmbraEngineering/Placeholder). We will use it later on the blog as well.

Responsive.gs is also shipped with two polyfills to enable certain features that are not supported in Internet Explorer 6, 7, and 8. From now on, let's refer to these browser versions as "old Internet Explorer", shall we?

HTML5 placeholder attribute

HTML5 introduced a new attribute named placeholder. The specs described this attribute as a

These new HTML elements make our document markup more descriptive and meaningful. Unfortunately, Internet Explorer 6, 7, and 8 will not recognize them. Thus, the selectors and style rules that address these elements are inapplicable; it is as if these new elements are not included in the Internet Explorer dictionary.

This is where a polyfill named HTML5Shiv comes into play. We will include HTML5Shiv (https://github.com/aFarkas/html5shiv) to make Internet Explorer 8 and its lower versions acknowledge these new elements. Read the following post (http://paulirish.com/2011/the-history-of-the-html5-shiv/) by Paul Irish for the history behind HTML5Shiv; how it was invented and developed.

Furthermore, older Internet Explorer versions won't be able to render the content in the HTML5 placeholder attribute. Fortunately, we can patch mimic the placeholder attribute functionality in the old Internet Explorer with a polyfill (https://github.com/UmbraEngineering/Placeholder). We will use it later on the blog as well.

Responsive.gs is also shipped with two polyfills to enable certain features that are not supported in Internet Explorer 6, 7, and 8. From now on, let's refer to these browser versions as "old Internet Explorer", shall we?

HTML5 in Internet Explorer

These new HTML elements make our document markup more descriptive and meaningful. Unfortunately, Internet Explorer 6, 7, and 8 will not recognize them. Thus, the selectors and

style rules that address these elements are inapplicable; it is as if these new elements are not included in the Internet Explorer dictionary.

This is where a polyfill named HTML5Shiv comes into play. We will include HTML5Shiv (https://github.com/aFarkas/html5shiv) to make Internet Explorer 8 and its lower versions acknowledge these new elements. Read the following post (http://paulirish.com/2011/the-history-of-the-html5-shiv/) by Paul Irish for the history behind HTML5Shiv; how it was invented and developed.

Furthermore, older Internet Explorer versions won't be able to render the content in the HTML5 placeholder attribute. Fortunately, we can patch mimic the placeholder attribute functionality in the old Internet Explorer with a polyfill (https://github.com/UmbraEngineering/Placeholder). We will use it later on the blog as well.

Responsive.gs is also shipped with two polyfills to enable certain features that are not supported in Internet Explorer 6, 7, and 8. From now on, let's refer to these browser versions as "old Internet Explorer", shall we?

A look into polyfills in the Responsive.gs package

Responsive.gs is also

shipped with two polyfills to enable certain features that are not supported in Internet Explorer 6, 7, and 8. From now on, let's refer to these browser versions as "old Internet Explorer", shall we?

Box sizing polyfills

The first polyfill is available
CSS3 media queries polyfill

The second polyfill script that comes along with Responsive.gs is respond.js (

Building a website is much the same as building a house; we need to examine the specification of every corner before we stack up all the bricks. So, before we jump in to building the blog, we will examine the blog's wireframe to see how the blog is laid out and also see the things that will be displayed on the blog.

Let's take a look at the following wireframe. This wireframe shows the blog layout when it is viewed on the desktop screen:

Examining the blog's wireframe

As you can see in the preceding screenshot, the blog will be plain and simple. In the header, the blog will have a logo and a search form. Down below the header, consecutively, we will place the menu navigation, the blog post, the pagination for navigating to the next or previous list of posts, and the footer.

The blog post, as in general, will comprise the title, the publishing date, the post's featured image, and the post excerpt. This wireframe is an abstraction of the blog's layout. We use it as our visual reference of how the blog layout will be arranged. So, in spite of the fact that we have shown only one post within the preceding wireframe, we will actually add a few more post items on the actual blog later on.

The following is the blog layout when the viewport width is squeezed:

Examining the blog's wireframe

When the viewport width gets narrow, the blog layout adapts. It is worth noticing that when we shift the layout, we should not alter the content flow as well as the UI hierarchy. Assuring the layout consistency between the desktop and the mobile version will help the users get familiar with a website quickly, regardless of where they are viewing the website. As shown in the preceding wireframe, we still have the UI set in the same order, albeit, they are now stacked vertically in order to fit in the limited area.

One thing that is worth mentioning from this wireframe is that the navigation turns into an HTML dropdown selection. We will discuss how to do so during the course of building the blog.

Now, as we have prepared the tools and checked out the blog layout, we are ready to start off the project. We will start off by creating and organizing the project directories and assets.

Perform the following steps to set up the project's working directory:

  1. Go to the htdocs folder. As a reminder, this folder is the folder in the local server located at:
    • C:\xampp\htdocs in Windows
    • /Applications/XAMPP/htdocs in OSX
    • /opt/lampp/htdocs in Ubuntu
  2. Create a new folder named blog. From now on, we will refer to this folder as the project directory.
  3. Create a new folder named css to store style sheets.
  4. Create a new folder named image to store images.
  5. Create a new folder named scripts to store JavaScript files.
  6. Create a new file named index.html; this HTML file will be the main page of the blog. Download the Responsive.gs package from http://responsive.gs/. The package comes in the .zip format. Extract the package to unleash the files within the package. There, you will find a number of files, including style sheets and JavaScript files, as you can see from the following screenshot:
    Time for action – creating and organizing project directories and assets

    The files that ship in Responsive.gs

  7. Move responsive.gs.12col.css to the css folder of the project directory; it is the only style sheet of Responsive.gs that we need.
  8. Move boxsizing.htc to the scripts folder of the project directory.
  9. The respond.js file that ships in the Responsive.gs package is out-of-date. Let's download the latest version of Respond.js from the GitHub repository (https://github.com/scottjehl/Respond/blob/master/src/respond.js) instead, and put it in the scripts folder of the project directory.
  10. Download HTML5Shiv from https://github.com/aFarkas/html5shiv. Put the JavaScript file html5shiv.js within the scripts folder.
  11. We will also use the placeholder polyfill that is developed by James Brumond (https://github.com/UmbraEngineering/Placeholder). James Brumond developed four different JavaScript files for cater to different scenarios.
  12. The script that we are going to use here is ie-behavior.js, because this script specifically addresses Internet Explorer. Download the script (https://raw.githubusercontent.com/UmbraEngineering/Placeholder/master/src/ie-behavior.js) and rename it as placeholder.js to make it more apparent that this script is a placeholder polyfill. Put it in the scripts folder of the project directory.
  13. The blog will need a few images to use as the post's featured image. In this module, we will use the images shown in the following screenshot, consecutively taken by Levecque Charles (https://twitter.com/Charleslevecque) and Jennifer Langley (https://jennifer-langley.squarespace.com/photography/):
    Time for action – creating and organizing project directories and assets
  14. We will add a favicon to the blog. A favicon is a tiny icon that appears on the browser tab beside the title, which will be helpful for readers to quickly identify the blog. The following is a screenshot that shows a number of pinned tabs in Chrome. I bet that you are still able to recognize the websites within these tabs just by seeing the favicon:
    Time for action – creating and organizing project directories and assets

    Google Chrome pinned tabs

  15. Further, we will also add the iOS icon. In Apple devices such as iPhone and iPad, we can pin websites on the home screen to make it quick to access the website. This is where the Apple icon turns out to be useful. iOS (the iPhone/iPad operating system) will show the icon we provide, as shown in the following screenshot, as if it was a native application:
    Time for action – creating and organizing project directories and assets

    Website added to the iOS home screen

  16. These icons are provided in the source files that come along with this module. Copy these icons and paste them in the image folder that we have just created in step 5, as shown in the following screenshot:
    Time for action – creating and organizing project directories and assets
What just happened?

We have just created a directory Have a go hero – making the directory structure more organized

Many people have their own preferences for how to organize their project's directory structure. The one shown Pop quiz – using polyfill

Earlier In this module, we discussed polyfill and also mentioned a few polyfill scripts that we are going to implement in the blog.

Q1. When do you

Perform the following steps to build the blog:

  1. Open the index.html file that we have created in step 6 of the previous section Time for action – creating and organizing project directories and assets. Let's start by adding the most basic HTML5 structure as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Blog</title>
    </head>
    <body>
      
    </body>
    </html>

    Here, set DOCTYPE, which has been brought to the bare minimum form. The DOCTYPE format in HTML5 is now shorter and cleaner than the DOCTYPE format of its HTML4 counterpart. Then, we set the language of our page, which in this case is set to en (English). You may change it to your local language; find the code for your local language at http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes.

    We have also set the character encoding to UTF-8 to enable the browser to render the Unicode characters, such as U+20AC, to the readable format .

  2. Below the charset meta tag in the head tag, add the following meta:
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    Internet Explorer can sometimes behave oddly, where it suddenly switches to compatibility mode and renders the page as viewed in Internet Explorer 8 and 7. This meta tag addition will prevent that from happening. It will force Internet Explorer to render the page with the highest support of the latest standards available in Internet Explorer.

  3. Below the http-equiv meta tag, add the following meta viewport tag:
    <meta name="viewport" content="width=device-width, initial-scale=1">

    As we mentioned in Chapter 1, Responsive Web Design, the preceding viewport meta tag specification defines the web page viewport width to follow the device viewport size. It also defines the web page scale at 1:1 upon opening the web page the first time.

  4. Link the Apple icon with the link tag, as follows:
    <link rel="apple-touch-icon" href="image/icon.png">

    As per Apple's official instructions, you would normally need to include multiple sources of icons to cater to iPhone, iPad, and the devices with a Retina screen. That isn't actually necessary for our blog. The trick is that we deliver the largest size required, which is 512 px square, through a single source, as shown in the previous screenshot.

  5. Add a description meta tag below the title, as follows:
    <meta name="description" content="A simple blog built using Responsive.gs">
  6. This description of the blog will show up in Search Engine Result Page (SERP). In this step, we will construct the blog header. First, let's add the HTML5 <header> element along with the classes for styling, to wrap the header content. Add the following within the body tag:
    <header class="blog-header row">
    
    </header>
  7. Within the <header> element that we added in step 9, add a new <div> element with the container and gutters class, as follows:
    <header class="blog-header row">
    <div class="container gutters">
    
    </div>
    </header>

    Referring to the table shown earlier in the chapter, the container class will align the blog header content to the center of the browser window, while the gutters class will add spaces between the columns, which we will add in the next steps.

  8. Create a new column to contain the blog logo/name with a <div> element along with the Responsive.gs col and span_9 class to set the <div> element as column and specify the width. Don't forget to add the class to add custom styles:
    <header class="blog-header row">
    <div class="container gutters">
           <div class="blog-name col span_9">
    <a href="/">Blog</a>
    </div>
    </div>
    </header>
  9. Referring to the blog wireframe, we will have a search form next to the blog logo/name. On that account, create another new column with a <div> element together with the col and span_3 class of Responsive.gs, and the input search type. Add the <div> element below the logo markup as follows:
    <header class="blog-header row">
    <div class="container gutters">
           <div class="blog-name col span_9">
       <a href="/">Blog</a>
    </div>
    <div class="blog-search col span_3">
               <div class="search-form">
                 <form action="">
     <input class="input_full" type="search"      placeholder="Search here...">
      </form>
                </div>
       </div>
    </div>
    </header>

    As we mentioned earlier in this chapter, we used an input search type to serve a better user experience. This input will show the mobile screen keyboard with a special key that allows users to hit the Search button and immediately run the search. We also added placeholder text with the HTML5 placeholder attribute to show the users that they can perform a search in the blog through the input field.

  10. After constructing the header blog, we will construct the blog navigation. Here we will use the HTML5 nav element to define a new section as navigation. Create a nav element along with the supporting classes to style. Add the nav element below the header construction as follows:
    ...     
    </div>
    </header> 
    <nav class="blog-menu row">
      
    </nav>
  11. Inside the nav element, create a div element with the container class to align the navigation content to the center of the browser window:
    <nav class="blog-menu">
    <div class="container">
    </div>
    </nav>
  12. In accordance to the wireframe, the blog will have five items on the link menu. We will lay out this link with the ul element. Add the links within the container, as shown in the following code snippet:
    <nav class="blog-menu row">
      <div class="container">
           <ul class="link-menu">
             <li><a href="/">Home</a></li>
             <li><a href="#">Archive</a></li>
             <li><a href="#">Books</a></li>
             <li><a href="#">About</a></li>
             <li><a href="#">Contact</a></li>
          </ul>
    </div>
    </nav>
  13. Having done with constructing the navigation, we will construct the content section of the blog. Following the wireframe, the content will consist a list of posts. First, let's add the HTML5 <main> element to wrap the content below the navigation as follows:
    ...
    </ul>  
    </nav>
    <main class="blog-content row">
      
    </main>

    We use the <main> element as we consider the posts as the prime section of our blog.

  14. Similar to the other blog sections—the header and the navigation—we add a container <div> to align the blog posts to the center. Add this <div> element within the <main> element:
    <main class="blog-content row">
       <div class="container">
    
    </div>
    </main>
  15. We will now create the blog post markup. Think of the blog post as an article. Thus, here we will use the <article> element. Add the <article> element within the container <div> that we will add in step 17 as follows:
    <main class="blog-content row">
    <div class="container">
      <article class="post row">
    
      </article>
    </div>
    </main>
  16. As mentioned, the <header> element is not limited to define a header. The blog can be used to define the head of a section. In this case, apart from the blog header, we will use the <header> element to define the articles head section that contains the article title and publishing date.
  17. Add the <header> element within the article element:
    <article class="post row">
    <header class="post-header">
    <h1 class="post-title">
    <a href="#">Useful Talks &amp; Videos for Mastering CSS</a>
      </h1>
          <div class="post-meta">
         <ul>
            <li class="post-author">By John Doe</li>
            <li class="post-date">on January, 10 2014</li>
         </ul>
         </div>
    </header>
    </article>
  18. A picture is worth a thousand words. So, it's the norm to use an image to support the post. Here, we will display the image below the post header. We will group the featured image together with the post excerpt as the post summary, as shown in the following code:
    ...
     </header>
     <div class="post-summary">
    <figure class="post-thumbnail">
    <img src="image/village.jpg" height="1508" width="2800" alt="">
    </figure>
    <p class="post-excerpt">Lorem ipsum dolor sit amet,   consectetur adipisicing elit. Aspernatur, sequi, voluptatibus, consequuntur vero iste autem aliquid qui et rerum vel ducimus ex enim quas!...<a href="#">Read More...</a></p>
      </div>
    </article>

    Add a few more posts subsequently. Optionally, you may exclude the post featured image in the other posts.

  19. After adding a pile of posts, we will now add the post pagination. The pagination is a form of common page navigation that allows us to jump to the next or previous list of posts. Normally, the pagination is located at the bottom of the page after the last post item.

    The pagination of a blog consists of two links to navigate to the next and previous page, and a small section to place the page numbers to show what page the user is currently in.

  20. So, add the following code after the last post:
    ...
    </article>
    <div class="blog-pagination">
    <ul>
      <li class="prev"><a href="#">Prev. Posts</a></li>
      <li class="pageof">Page 2 of 5</li>
      <li class="next"><a href="#">Next Posts</a></li>
    </ul>
    </div>
  21. Finally, we will construct the blog footer. We can define the blog footer using the HTML5 <footer> element. The footer structure is identical to the one for the header. The footer will have two columns; each respectively contains the blog footer links (or, as we call it, secondary navigation) and copyright statement. These columns are wrapped with a <div> container. Add the following footer in the main section, as follows:
          …
    </main> 
    <footer class="blog-footer row">
       <div class="container gutters">
         <div class="col span_6">
    <nav id="secondary-navigation"  class="social-   media">
              <ul>
               <li class="facebook">
    <a href="#">Facebook</a>
      </li>
               <li class="twitter">
    <a href="#">Twitter</a></li>
               <li class="google">
    <a href="#">Google+</a>
       </li>
             </ul>
           </nav>
         </div>
       <div class="col span_6">
    <p class="copyright">&copy; 2014. Responsive  Blog.</p>
       </div>
       </div>
    </footer>
What just happened?

We have just finished constructing the blog's HTML structure—the header, the navigation, the Have a go hero – creating more blog pages

In this module, we only build the blog's home page. However, you are free to extend the blog by creating more pages, such as adding an about page, a single post content page, and a page with a Pop quiz – HTML5 elements

Let's end this chapter with simple questions regarding HTML5:

Q1. What is the <header> element used for?

It is used to represent the website header.
It is used to represent a group of introductory and navigational aids.

Q2. What is the <footer> element used for?

It is used to represent the website footer.
It is used to represent the end or the lowest part of a section.

Q3. Is it allowed to use the <header> and <footer> elements multiple times within a single page?

Yes, as long as it's semantically logical.
No, it's considered redundant.
 

In the previous chapter, we constructed the blog markup from the header section to the footer section using HTML5 elements. The blog, however, is currently faceless. If you opened the blog in a browser, you will just see it bare; we have not yet written the styles that add up to its appearance.

Throughout the course of this chapter, we will focus on decorating the blog with CSS and JavaScript. We will be using CSS3 to add the blog styles. CSS3 brings a number of new CSS properties, such as border-radius, box-shadow, and box-sizing, that allow us to decorate websites without the need to add images and extra markup.

However, the CSS properties, as mentioned previously, are applicable only within the latest browser versions. Internet Explorer 6 to 8 are not able to recognize those CSS properties, and won't be able to output the result in the browsers. So, as an addition, we will also utilize a number of polyfills to make our blog presentable in the old Internet Explorer.

It's going to be an adventurous chapter. Let's go.

In this chapter, we shall cover the following topics:

CSS3 ships with long-awaited properties, border-radius and box-shadow, that simplify old and tedious methods that were used to present rounded corner and drop shadow in HTML. On top of that, it also brings a new type of pseudo-element that enables us to style the placeholder text shown in input fields through the HTML5 placeholder attribute.

Let's take a look at how they work.

Back in the 90s, creating a rounded corner was complicated. Adding a pile of HTML markup, slicing out images, and formulating multiple line style of rules is inevitable, as presented in the post by Ben Ogle at http://benogle.com/2009/04/29/css-round-corners.html.

CSS3 makes it much simpler to create rounded corners with the border-radius property, and the following is an example:

div {
  width: 100px; height: 100px;
  border-radius: 30px;
}

The preceding style rule will round the box corner (read the A word on CSS Box Model section in Chapter 1, Responsive Web Design) each for 30px, as shown in the following figure:

Creating rounded corners with CSS3

Furthermore, we can also round only to specific corners. The following code snippet, for example, will round only the top-right corner:

Much the same as creating rounded corners, using images was unavoidable to create shadow effects in the website in the past. Now, adding a drop shadow has been made easy with the introduction of the box-shadow property. The box-shadow property consists of five parameters (or values):

The first parameter specifies where the shadow takes place. This parameter is optional. Set the value to inset to let the shadow appear inside the box or leave it empty to display the shadow outside.

The second parameter specifies the shadow vertical and horizontal distance from the box.

The third parameter specifies the shadow blur that fades the shadow; a bigger number will produce a bigger but faded shadow.

The fourth parameter specifies the shadow expansion; this value is slightly contradicted to the shadow blur value. This value will enlarge yet also intensify the shadow depth.

The last parameter specifies the color. The color can be in any web-compatible color format, including Hex, RGB, RGBA, and HSL.

Carrying on the preceding example, we can add up box-shadow, as follows:

The preceding code will output the shadow, as shown in the following figure:

Creating drop shadow

Add inset at the beginning if you want to show the shadow inside the box, as follows:

Both the border-radius and box-shadow properties have been well-implemented in many browsers. Technically, if we would cater only to the latest browser versions, we do not need to include the so-called vendor prefix.

Yet, if we intend to enable these two properties, border-radius and box-shadow, back in the earliest browser versions, where they were still marked as experimental by the browser vendors such as Safari 3, Chrome 4, and Firefox 3, adding the vendor prefix is required. Each browser has its prefix as follows:

Let's carry on our previous examples (again). With the addition of the vendor prefix to cater to the earliest versions of Chrome, Safari, and Firefox, the code would be as follows:

The code may turn out to be a bit longer; still it is preferable over having to cope with complicated markups and multiple style rules.

Note

Chrome and its new browser engine, Blink

Chrome decided to fork Webkit and built its own browser engine on top of it, named Blink (http://www.chromium.org/blink). Opera, which previously discarded its initial engine (Presto) for Webkit, follows along the Chrome movement. Blink eliminates the use of the vendor prefix, so we would not find -blink- prefix or such like. In Chrome's latest versions, instead of using the vendor prefix, Chrome disables experimental features by default. Yet, we can enable it through the options in the chrome://flags page.

With the addition of HTML5, the placeholder attribute brings the question of how to customize the placeholder text. By default, browsers display the placeholder text with a light gray color. How do we change, for example, the color or the font size?

At the time of writing this, each browser has its own way in this regard. WebKit-based browsers, such as Safari, Chrome, and Opera, use ::-webkit-input-placeholder. Internet Explorer 10 uses :-ms-input-placeholder. Firefox 4 to 18, on the other hand, use pseudo-class, :-moz-placeholder, but it has then been replaced with the pseudo-element ::-moz-placeholder (notice the double colons) since Firefox 19 to keep up with the standard.

These selectors cannot be used in tandem within a single style rule. So, the following code snippet will not work:

They have to be declared in a single style rule declaration, as follows:

This is definitely inefficient; we added extra lines only to achieve the same output. There isn't another viable option at the moment. The standard for styling the placeholder is still in discussion (see the CSSWG discussion at http://wiki.csswg.org/ideas/placeholder-styling and http://wiki.csswg.org/spec/css4-ui#more-selectors for more details).

Once we have explored all the things that we are going to include in this project, let's set up the tool to put them together. In Chapter 1, Responsive Web Design, we have installed Koala. Koala is a free and open source development tool that ships with many features. In this first project, we will use Koala to compile style sheets and JavaScripts into a single file, as well as minify the codes to result in a smaller file size.

There will be about five style sheets that we are going to include in the blog. If we load all these style sheets separately, the browsers will have to pull off five HTTP requests, as shown in the following screenshot:

Working with Koala

As shown in the preceding screenshot, the browser performs five HTTP requests to load all the style sheets, which have a size of 24.4 KB in total and require around 228 ms in total to load.

Combining these style sheets into a single file and squishing the codes therein will speed up the page-load performance. The style sheet can also become significantly smaller, which eventually will also save bandwidth consumption.

As shown in the following screenshot, the browser only performs one HTTP request; the style sheet size is reduced to 13.5KB, and takes only 111 ms to load. The page loads about 50 percent faster in comparison with the preceding example:

Working with Koala

In this section, we will integrate the configured Koala to compile and output the style sheets, by performing the following steps:

  1. Create a new style sheet in the css folder named main.css. This is the prime style sheet, where we will compose our own style rules for the blog.
  2. Create a new style sheet named style.css.
  3. Download normalize.css (http://necolas.github.io/normalize.css/), and put it in the css folder of the project directory.
  4. Download formalize.css (http://formalize.me/), and also put it in the css folder of the project directory.
  5. Open style.css in Sublime Text.
  6. Import the supporting style sheets using the @import rule in the following order, as follows:
    @import url("css/normalize.css");
    @import url("css/formalize.css");
    @import url("css/responsive.gs.12col.css");
    @import url("css/main.css");
    @import url("css/responsive.css");
  7. Launch Koala. Then, drag-and-drop the project directory into the Koala sidebar. Koala will show and list recognizable files, as shown in the following screenshot:
    Time for action – integrating project directory into Koala and combining the style sheets
  8. Select style.css and tick Auto Compile to compile style.css automatically whenever Koala detects a change in it. Have a look at the following screenshot:
    Time for action – integrating project directory into Koala and combining the style sheets
  9. Select the Combine Import option to let Koala combine the content within the style sheets (the content that was included in style.css) with the @import rule. Take a look at the following screenshot:
    Time for action – integrating project directory into Koala and combining the style sheets
  10. Set Output Style: to compress. Take a look at the following screenshot:
    Time for action – integrating project directory into Koala and combining the style sheets

    This will compress the style rules into a single line, which eventually will make the style.css file size smaller.

  11. Click on the Compile button. Take a look at the following screenshot:
    Time for action – integrating project directory into Koala and combining the style sheets

    This will compile style.css and generate a new file named style.min.css as the output.

  12. Open index.html and link style.min.css. using the following code:
    <link href="style.min.css" rel="stylesheet">
What just happened?

We have just integrated the project directory within Koala. We have also created two new style sheets, namely, main.css and style.css. We have also put together five style sheets, including main.css, in the style.css file using the @import rule. We combined these files and generated a new style sheet named style.min.css, which can be found inline with style.css, as shown in the following screenshot:

What just happened?

Finally, we link the minified style sheet, style.min.css, in index.html. Have a go hero – renaming the output

The style.min.css name is the default name set by Koala; it inserts the suffix, min, to every minified output. Though Pop quiz – website performance rules

Q1. Which of the following rules is not the one to improve website performance?

Minifying resources such as CSS and JavaScript.
Compressing image files.
Leveraging browser cache.
Using CSS shorthand properties.
Using CDN to deliver web resources.

Before we get our hands on the code, let's talk about the mobile-first approach that will drive our decision on writing part of the blog style rules.

Mobile-first is one of the buzzwords in the web design community. Mobile-first is a new way of thinking on building websites of today, which also guides the pattern to build websites that are optimized for mobile use. As mentioned in Chapter 1, Responsive Web Design, mobile users are growing and desktop is no longer the main platform where users can access the web.

The mobile-first concept drives us to think and prioritize mobile use on building the website blocks, including how we compose style rules and media queries. In addition, adopting mobile-first thinking, as Brad Frost demonstrated in his blog post (http://bradfrostweb.com/blog/post/7-habits-of-highly-effective-media-queries/), allows producing leaner codes than the other way around (desktop to mobile). Herein, we will first optimize and address the blog for mobile and then enhance to the desktop version afterwards.

Mobile-first is beyond the capacity of this module, we'll make Mobile-first web applications later in Module 3, HTML5 and CSS3 Responsive Web Design Cookbook. The following are some of my recommendation sources to dig into this topic further:

In this section, we are going to write blog base styles. These style rules encompass the content font family, the font size, and a number of elements therein in general.

First of all, it is my personal opinion that using the default system font such as Arial and Times is so boring.

Perform the following steps to compose the base style rules:

  1. To make our blog look more refreshing, we will use a couple of custom fonts from the Google Font library. Google Font has made it easy for us to use fonts on the Web. Google has taken care of the hassle of writing the syntax, as well as ensuring that the font formats are compatible in all major browsers.
  2. In addition, we won't be befuddled with the font license, as Google Font is completely free. All we have to do is add a special style sheet as explained in this page https://developers.google.com/fonts/docs/getting_started#Quick_Start. In our case, add the following link before the prime style sheet link:
    <link href='http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic|Varela+Round' rel='stylesheet'>

    Upon doing so, we will be able to use the Droid Serif font family, along with Varela Round; see these font specimens and characters in the following web pages:

  3. Set the entire element box sizing to border-box. Add the following line (as well as the other lines in the next steps) in main.css:
    * { 
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      box-sizing: border-box;
      *behavior: url(/scripts/boxsizing.htc);
    }
  4. We are going to set the blog main font, that is, the font that applies to the entire content of the blog. Herein, we will use Droid Serif of Google Font. Add the following style rules after the list of @import style sheet:
    body {
      font-family: "Droid Serif", Georgia, serif;
      font-size: 16px;
    }
  5. We are going to apply a different font family for the headings (h1, h2, h3, h4, h5, and h6) in order to set it apart from the body content. Herein, we will apply the second custom font family that we brought from the Google Font collection, Varela Round.
  6. Add the following line to apply Varela Round to the headings:
    h1, h2, h3, h4, h5, h6 {
        font-family: "Varela Round", Arial, sans-serif;
        font-weight: 400;
    }
  7. In this step, we will also customize the default anchor tag or link styles. It's my personal preference to remove the underline of the default link style.

    Furthermore, we also change the link color to #3498db. It's blue, but subtler than the blue color applied as the default link style, as shown in the following screenshot:

    Time for action – composing the base style rules
  8. Add the following lines to change the default link color:
    a {
        color: #3498db;
        text-decoration: none;
    }
  9. We will set the color of the link to hover state, as well. This color appears when the mouse cursor is over the link. Herein, we set the link hover color to #2a84bf, the darker version of the color we set in step 4. Have a look at the following screenshot:
    Time for action – composing the base style rules
  10. Add the following line to set the color of the link when it is in hover state, as follows:
    a:hover {
        color: #2a84bf;
    }
  11. Make the image fluid with the following style rules, as follows:
    img {
      max-width: 100%;
      height: auto;
    }

In addition, these style rules will prevent the image from exceeding its container when the actual image width is larger than the container.

Please note that the link color, #2a84bf, is my personal selection. There are a number of considerations when choosing a color, such as the brand, the audience, and the content. The link doesn't have to be #2a84bf. The link color in the Starbucks website (http://www.starbucks.co.id/about-us/pressroom), for example, is green, which refers to its brand identity.

So, don't be afraid to explore and try new colors. The following are a few color ideas:

Have a go hero – customizing the link color

Next, we will compose the blog header and navigation style rules. The style rules will mostly be applied through the element's classes. So, before proceeding, please refer to Chapter 2, Web Development Tools, to see the class names and ID that we added in the elements.

What just happened?

We have just added style rules that address some elements in the blog, namely, the headings, the link, and the image. At this stage, there isn't a significant difference yet that appears in the blog, except the font family change in the content and the headings, as well as the link color. Have a look at the following screenshot:

What just happened?

Please note that the link color, #2a84bf, is my personal selection. There are a number of considerations when choosing a color, such as the brand, the audience, and the content. The link doesn't have to be #2a84bf. The link color in the Starbucks website (http://www.starbucks.co.id/about-us/pressroom), for example, is green, which refers to its brand identity.

So, don't be afraid to explore and try new colors. The following are a few color ideas:

Have a go hero – customizing the link color

Next, we will compose the blog header and navigation style rules. The style rules will mostly be applied through the element's classes. So, before proceeding, please refer to Chapter 2, Web Development Tools, to see the class names and ID that we added in the elements.

Have a go hero – customizing the link color

Please note that the link color, #2a84bf, is my personal selection. There are a number of considerations

when choosing a color, such as the brand, the audience, and the content. The link doesn't have to be #2a84bf. The link color in the Starbucks website (http://www.starbucks.co.id/about-us/pressroom), for example, is green, which refers to its brand identity.

So, don't be afraid to explore and try new colors. The following are a few color ideas:

Have a go hero – customizing the link color

Next, we will compose the blog header and navigation style rules. The style rules will mostly be applied through the element's classes. So, before proceeding, please refer to Chapter 2, Web Development Tools, to see the class names and ID that we added in the elements.

The steps are as follows:

  1. Open main.css.
  2. Add some whitespace surrounding the header with padding, and also set the header color to #333, as follows:
    .blog-header {
    padding: 30px 15px;
    background-color: #333;
    }
  3. To make the logo look prominent, we will set it with Varela Round font, which is the same font family we used for the headings. We also make it bigger and transform the letters all to uppercase, as follows:
     .blog-name {
      font-family: "Varela Round", Arial, sans-serif;
      font-weight: 400;
      font-size: 42px;
      text-align: center;
      text-transform: uppercase;
    }
  4. The logo link color currently is #2a84bf, which is the common color we set for links <a>. This color does not suit well with the background color. Let's change the color to white instead, as follows:
    .blog-name a {
        color: #fff;
    }
  5. Set the search input styles, as follows:
    .search-form input {
      height: 36px;
      background-color: #ccc;
      color: #555;
      border: 0;
      padding: 0 10px;
      border-radius: 30px;
    }

    These style rules set the input color, border color, and the background colors. It turns the input into something as shown in the following screenshot:

    Time for action – enhancing the header and the navigation appearance with CSS
  6. As you can see in the preceding screenshot, the placeholder text is barely readable as the color blends with the input background color. So, let's make the text color a bit darker, as follows:
    .search-form input::-webkit-input-placeholder {
      color: #555;
    }
    .search-form input:-moz-placeholder {
      color: #555;  
    }
    .search-form input::-moz-placeholder {
      color: #555;  
    }
    .search-form input:-ms-input-placeholder {  
      color: #555;
    }

    If you use OS X or Ubuntu, you will see the glowing color that highlights the input when it is currently targeted, as shown in the following screenshot:

    Time for action – enhancing the header and the navigation appearance with CSS

    In OS X, the glowing color is blue. In Ubuntu, it will be orange.

  7. I would like to remove this glowing effect. The glowing effect is technically shown through box-shadow. So, to remove this effect, we simply set the input box-shadow to none, as follows:
    .search-form input:focus {
      -webkit-box-shadow: none;
      -moz-box-shadow: none;
      box-shadow: none;
    }

    It's worth noting that the glowing effect is part of the User Experience (UX) design, telling the users that they are currently within the input field. This UX design is particularly helpful if the users were only able to navigate the website with a keyboard.

  8. So, we will have to create an effect that brings a similar UX as a replacement. Herein, we will replace the glowing effect that we removed by lightening the input background color. The following is the complete code of this step:
    .search-form input:focus {
      -webkit-box-shadow: none;
      -moz-box-shadow: none;
      box-shadow: none;
      background-color: #bbb;
    }

    The input background color becomes lighter when it is in focus, as shown in the following screenshot:

    Time for action – enhancing the header and the navigation appearance with CSS
  9. We will write the style for the navigation. First, align the menu to the center, and add some whitespace at the top and the bottom of the navigation with the margin. Have a look at the following code:
    .blog-menu {
      margin: 30px 0;
      text-align: center;
    }
  10. Remove the left-hand side padding of <ul>, as follows:
    .blog-menu ul {
      padding-left: 0;
    }
  11. Add some whitespace between the menus with a margin, and remove the list bullet, as follows:
    .blog-menu li {
      margin: 15px;
      list-style-type: none;
    }
  12. Customize the menu color and font, as follows:
    .blog-menu a {
      color: #7f8c8d;
      font-size: 18px;
       text-transform: uppercase;
       font-family: "Varela Round", Arial, sans-serif;
    }
    .blog-menu a:hover {
        color: #3498db;
    }
What just happened?

We have just Have a go hero – customizing the header

The blog header is given a dark color, #333. I truly understand that this color may look boring to some of you. Hence, freely customize the color as well as the style of the logo and the search input field. Some

Perform the following steps to style the blog content:

  1. Add whitespace on all sides of the content section with padding and margin, as follows
    .blog-content {
      padding: 15px;
      margin-bottom: 30px;
    } 
  2. Separate each blog post with some whitespace and borderline, as follows:
    .post {
      margin-bottom: 60px;
      padding-bottom: 60px;
      border-bottom: 1px solid #ddd;
    }
  3. Align the title to the center, adjust the title font size a little, and change the color with the following style rules:
    .post-title {
      font-size: 36px;
      text-align: center;
      margin-top: 0;
    }
    .post-title a {
      color: #333;
    }
    .post-title a:hover {
      color: #3498db;
    }
  4. Below the title, we have post-meta, which consists of the post author name and the post publishing date. Similar to the title, we also adjust the font size and the whitespace, and change the font color, as follows:
    .post-meta {
      font-size: 18px;
      margin: 20px 0 0;
      text-align: center;
      color: #999;
    }
    .post-meta ul {
      list-style-type: none;
      padding-left: 0;
    }
    .post-meta li {
      margin-bottom: 10px;
    }
  5. The post thumbnail, as you can see in the following screenshot, looks small and squished due to the margin on all its sides:
    Time for action – enhancing the content section appearance with CSS
  6. Let's remove these margins, as follows:
    .post-thumbnail {
      margin: 0;
    }

    Some of the images, as shown in the following screenshot, have a caption:

    Time for action – enhancing the content section appearance with CSS
  7. Let's style it to make it look distinctive from the rest of the content and also show that it is an image caption. Add the following lines of code to style the caption:
    .post-thumbnail figcaption {
      color: #bdc3c7;
      margin-top: 15px;
      font-size: 16px;
      font-style: italic;
    }
  8. Adjust the post excerpt font size, color, and line height, as follows:
    .post-excerpt {
      color: #555;
      font-size: 18px;
      line-height: 30px;
    }
  9. Starting in this step, we will write the style of the blog pagination. First, let's make some adjustments to the font size, the font family, the whitespace, the position, and the alignment, as shown in the following code:
    .blog-pagination {
      text-align: center;
      font-size: 16px;
      position: relative;
      margin: 60px 0;
    }
    .blog-pagination ul {
      padding-left: 0;
    }
    .blog-pagination li,
    .blog-pagination a {
      display: block;
      width: 100%;
    }
    .blog-pagination li {
      font-family: "Varela Round", Arial, sans-serif;
      color: #bdc3c7;
      text-transform: uppercase;
      margin-bottom: 10px;
    }
  10. Decorate the pagination link with rounded corner borders, as follows:
    .blog-pagination a {
      -webkit-border-radius: 30px;
      -moz-border-radius: 30px;
      border-radius: 30px;
      color: #7f8c8d;
      padding: 15px 30px;
      border: 1px solid #bdc3c7;
    }
  11. Specify the link decoration when the mouse cursor hovers over the links, as follows:
    .blog-pagination a:hover {
      color: #fff;
      background-color: #7f8c8d;
      border: 1px solid #7f8c8d;
    }
  12. Finally, place the page number indicator at the top of the pagination links with the following style rules:
    .blog-pagination .pageof {
      position: absolute;
      top: -30px;
    }
What just happened?

We just styled the blog Have a go hero – improving the content section

Most of the style rules we applied in the content section are decorative. It's something that you don't have to follow What just happened?

We have just

Perform the following steps to compose style rules for desktop:

We will add all the style rules in the following steps within this media query. This media query specification will apply the style rules within the viewport width starting from 640 px and up.

What just happened?

We have just added style rules that address the blog for the desktop view. If you are now viewing the blog in the viewport width that is larger than 640 px, you should find that the elements in the blog

Perform the steps to patch Internet Explorer with polyfills:

What just happened?

We just applied polyfills in the blog to patch Internet Explorer rendering issues with HTML5 and Media Have a go hero – polish the blog for Internet Explorer

We will end this project. But, as you can see from the preceding screenshot, there are still many things to address
 

Bootstrap (http://getbootstrap.com/) is one of the sturdiest frontend development frameworks. It ships with amazing features, such as a responsive grid, user interface components, and JavaScript libraries that let us build responsive websites up and running quickly.

Bootstrap is so popular that the web development community positively supports it by developing extensions in a variety of forms to add extra features. In case the standard features that come with Bootstrap are not sufficient, there can be an extension to cover your particular requirements.

In this chapter, we will start our second project. We will employ Bootstrap to build a responsive portfolio website. So, this chapter apparently would be useful for those who work in creative fields such as photography, graphic design, and illustrating.

Herein, we will also employ a Bootstrap extension to empower the portfolio website with off-canvas navigation. Following Bootstrap, we will turn to LESS as the foundation of the website style sheets.

Let's move on.

The discussion that we are going to cover in this chapter will include the following topics:

Unlike the Responsive.gs framework that we used in the first project, Bootstrap is shipped with extra components, which are commonly used in the Web. Hence, before we step further into developing the portfolio website, first let's explore these components, mainly those of which we will employ within the website, such as the responsive grid, the buttons, and the form elements.

Note

Frankly, the official Bootstrap website (http://getbootstrap.com/) is always the best source to be up-to-date with anything related to Bootstrap. So, herein, I would like to point out the key things that are straightforward.

Bootstrap comes with a Responsive Grid System, along with the supporting classes that form the columns and the rows. In Bootstrap, we build the column using these prefix classes: col-xs-, col-sm-, col-md-, and col-lg-. This is then followed by the column number, ranging from 1 to 12, to define the column size as well as to aim the column for a specific viewport size. See the following table for more detail on the prefixes:

In the following example, we set out three columns in a row, with each column assigned a col-sm-4 class:

So, each column will have the same size, and they will scale down up to the Bootstrap-defined small viewport size (≥ 768px). The following screenshot shows how the preceding markup turns out in the browser (by adding a few styles):

The Bootstrap responsive grid

View the example in the viewport size, which is smaller than 768 px, and all these columns will start to stack up—the first column at the top and the third column at the very bottom, as shown in the following screenshot:

The Bootstrap responsive grid

Furthermore, we can add multiple classes to specify the column proportion within multiple viewport sizes, as follows:

Given the preceding example, the columns will have the same size within the Bootstrap-defined large viewport size (≥ 1,200 px), as shown in the following screenshot:

The Bootstrap responsive grid

The column proportion then starts to shift when we view it in the medium viewport size following the assigned classes on each column. The first column width will become smaller, the second column will retain the same proportion, while the third column will be larger, as shown in the following screenshot:

The Bootstrap responsive grid

The column proportion will start to shift again when the website is at the threshold of the Bootstrap-defined medium- and small-viewport size, which is approximately at 991px, as shown in the following screenshot:

The Bootstrap responsive grid

Other components that we will incorporate into the website are buttons and forms. We will create an online contact through which users will be able get in touch. In Bootstrap, the button is formed with the btn class followed by btn-default to apply Bootstrap default styles, as shown in the following code:

Replace the btn-default class with btn-primary, btn-success, or btn-info to give the buttons the colors specified, as shown in the following code:

The code snippet defines the button size with these classes: btn-lg to make the button large, btn-sm to make it small, and btn-xs to make the button even smaller, as shown in the following code:

The following screenshot shows how the button-size changes with the look, when the preceding classes are added:

Bootstrap buttons and forms

Bootstrap allows us to display buttons in a number of ways, such as displaying a series of buttons inline together or adding a dropdown toggle in a button. For further assistance and details on constructing these types of buttons, head over to the button groups (http://getbootstrap.com/components/#btn-groups) and the button dropdown (http://getbootstrap.com/components/#btn-dropdowns) sections of Bootstrap's official website.

Bootstrap buttons and forms

The Bootstrap buttons groups and buttons with a dropdown toggle

Bootstrap also provided a handful of reusable classes to style the form elements, such as <input> and <textarea>. To style the form elements, Bootstrap uses the form-control class. The style is light and decent, as shown in the following screenshot:

Bootstrap buttons and forms

For more information regarding styling and arranging the form element in Bootstrap, refer to the form section of the Bootstrap official page (http://getbootstrap.com/css/#forms).

Bootstrap describes Jumbotron as follows:

Jumbotron is a special section to display the website's first-line message, such as the marketing copy, catchphrases, or special offers, and additionally a button. Jumbotron is typically placed above the fold and below the navigation bar. To construct a Jumbotron section in Bootstrap, apply the jumbotron class, as follows:

<div class="jumbotron">
  <h1>Hi, This is Jumbotron</h1>
<p>Place the marketing copy, catchphrases, or special offerings.</p>
  <p><a class="btn btn-primary btn-lg" role="button">Got it!</a></p>
</div>

With the Bootstrap default styles, the following is how the Jumbotron looks:

It's impossible to cater to everyone's needs, and the same thing applies to Bootstrap as well. A number of extensions are created in many forms—from CSS, JavaScript, icons, starter templates, and themes—to extend Bootstrap. Find the full list on this page (http://bootsnipp.com/resources).

In this project, we will include an extension named Jasny Bootstrap (http://jasny.github.io/bootstrap/), developed by Arnold Daniels. We will use it primarily to incorporate off-canvas navigation. The off-canvas navigation is a popular pattern in responsive design; the menu navigation will first set off the visible area of the website and will only slide-in typically by clicking or tapping, as illustrated in the following screenshot:

Jasny Bootstrap is an extension that adds extra building blocks to the original Bootstrap. Jasny Bootstrap is designed with Bootstrap in mind; it follows Bootstrap conventions in almost every aspect of it, including the HTML markups, the class naming, and the JavaScript functions as well as the APIs.

As mentioned, we will use this extension to include off-canvas navigation in the portfolio website. The following is an example code snippet to construct off-canvas navigation with Jasny Bootstrap:

As you can see from the preceding code snippet, constructing off-canvas navigation requires a bunch of HTML elements, classes, and attributes in the mix. To begin with, we need two elements, <nav> and <div>, to contain respectively the menu and the button to toggle the navigation menu on and off. The <nav> element is given an ID as a unique reference of which menu to target via the data-target attribute in <button>.

A handful of classes and attributes are added within these elements to specify the colors, backgrounds, position, and functions:

In this section, we are going to add the project dependencies that include the Bootstrap, Jasny Bootstrap, Ionicons, and HTML5Shiv. We will install them using Bower so that we are able to maintain them—remove and update them—more seamlessly in the future.

In addition, since this might be the first time for many of you using Bower, I will walk you through the process at a slow pace, bit by bit. Please perform the following steps thoroughly:

  1. In the htdocs folder, create a new folder, and name it portfolio. This is the project directory, where we will add all project files and folders to.
  2. In the portfolio folder, create a new folder named assets. We will put the project assets, such as image, JavaScript, and style sheet in this folder.
  3. In the assets folder, create these following folders:
    • img to contain the website images and image-based icons
    • js to contain the JavaScript files
    • fonts to contain the font icon set
    • less to contain the LESS style sheets
    • css as the output folder of LESS
  4. Create index.html as the website's main page.
  5. Add the images for the website in the img folder; this includes the portfolio images and the icons for a mobile device, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower

    Note

    This website has around 14 images including the icons for mobile devices. I would like to thank my friend Yoga Perdana (https://dribbble.com/yoga) for allowing me to use his wonderful work In this module. You can find these images bundled along with this module. But, certainly, you can replace them with your very own images.

  6. We will install the dependencies—packages, libraries, JavaScript, or CSS that are required to run the project, as well as to build the website—through Bower. But, before running any Bower command to install the dependencies, we would like to set the project as a Bower project using the bower init command to define the project specification in bower.json, such as the project name, the version, and the author.
  7. To begin with, open a terminal or command prompt if you are using Windows. Then, navigate to the project directory using the cd command, as follows:
    • In Windows: cd \xampp\htdocs\portfolio
    • In OS X: cd /Applications/XAMPP/htdocs/portfolio
    • In Ubuntu: cd /opt/lampp/htdocs/portfolio
  8. Type bower init, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  9. First, we specify the project name. In this case, I would like to name the project responsive-portfolio. Type the name as follows, and press Enter to proceed. Have a look at the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  10. Specify the project version. Since the project is new, let's simply set it to 1.0.0, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  11. Press Enter to proceed.
  12. Specify the project description. This prompt is entirely optional. You may leave it empty if you think it's not required for your project. In this case, I will describe the project as a responsive portfolio website built with Bootstrap, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  13. Specify the main file of the project. This certainly will vary depending on the project. Herein, let's set the main file to index.html, the website's home page, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  14. This prompts the question, "what types of modules does this package expose?" It specifies what the package is used for. In this case, simply select the global option, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  15. Press the Space Bar key to select it, and press Enter to continue.
  16. The keywords prompt tells the project relation. In this case, I would like to fill it as portfolio, responsive, bootstrap, as shown in the following screenshot. Press Enter to continue:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower

    The keywords prompt is optional. You can leave it empty if you want by pressing the Enter key with the value left empty.

  17. The authors prompt specifies the author of the project. This prompt is prepopulated with your computer user name and e-mail that you have registered in the system. Yet, you can overwrite it by specifying a new name and pressing Enter to continue, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  18. Specify the project license. Herein, we will simply set it to the MIT license. The MIT license grants anyone to do whatever he or she wants with the code in the project, including modification, sublicensing, and commercial use. Have a look at the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  19. Specify the home page of the project. This could be your own website repository. In this case, I would like to set it with my personal domain, creatiface.com, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  20. In the set currently installed components as dependencies?: command, type n (no), as we haven't installed any dependencies or packages yet, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  21. The Add commonly ignored files to ignore list? command will create the .gitignore file containing a list of common files to exclude from the Git repository. Type Y for yes. Have a look at the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  22. For the would you like to mark this package as private which prevents it from being accidentally published to the registry? command type Y as we won't register our project to the Bower registry. Have a look at the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  23. Examine the output. If it looks good, type Y to generate the output within the bower.json file, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  24. There are a number of libraries we want to install. To begin with, let's install Bootstrap with the bower install bootstrap ––save command, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower

    The --save parameter following the command will register Bootstrap as the project dependency in bower.json. If you open it, you should find it recorded under the dependencies, as shown in the following screenshot:

    Time for action – organizing project directories, assets, and installing project dependencies with Bower

    You should also find the Bootstrap package saved in a new folder, bower_components, along with jQuery, which is a Bootstrap dependency, as shown in the following screenshot:

    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  25. Install the Bootstrap extension, Jasny Bootstrap, with the bower install jasny-bootstrap –save command.
  26. Install Ionicons with the LESS style sheet, with the bower install ionicons command.
  27. The Ionicons package ships with the font files. Move them to the fonts folder of the project directory, as shown in the following screenshot:
    Time for action – organizing project directories, assets, and installing project dependencies with Bower
  28. Finally, install HTML5Shiv to enable the new elements of HTML5 in Internet Explorer 8 and below, with the bower install html5shiv ––save command.
What just happened?

We just created folders and the website home page document, index.html. Images and icons that are going to be displayed on the website are also prepared. We also recorded the project specification in bower.json. Through this file, we can tell that the project is named responsive-portfolio, currently at version 1.0.0, and has a couple of dependencies, as follows:

Bootstrap

We have downloaded these libraries via the bower install command, which is leaner than having to download and extract the .zip package. All the libraries should have been added within a folder named bower_components, as shown in the following screenshot:

What just happened?
Have a go hero – specifying Bower custom directory

Bower, by default, creates
Pop quiz – test your understanding on Bower commands

Q1. We have shown you how to install and update libraries with Bower. The question now is: how to remove the library that has been installed?

Run the bower remove command.
Run the bower uninstall command.
Run the bower delete command.

Q2. Besides installing and removing the library, we can also search the availability of the library in the Bower registry. How to search a library through the Bower registry?

Run bower search followed by a keyword.
Run bower search followed by the library name.
Run bower browse followed by a keyword.

Q3. Bower also allows us to look into the detail of the package properties, such as the package version, dependencies, author, etc. What command do we perform to look into these details?

bower info.
bower detail.
bower property. Updating Bower components

As the dependencies

In this section, we are going to build the website's HTML structure. You will find that a few of the elements that we are going to add herein will be similar to the ones we added in the first website, responsive blog. Hence, the following steps will be straightforward. If you have followed the first through to the end, these steps should also be easy to follow. Let's carry on.

  1. Open index.html. Then, add the basic HTML structure, as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Portfolio</title>
    </head>
    <body>
      
    </body>
    </html>
  2. Below <meta charset="UTF-8">, add a meta tag to address the Internet Explorer rendering compatibility:
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    The preceding meta tag specification will force Internet Explorer to use the latest engine's version therein to render the page.

  3. Below the http-equiv meta tag, add the meta viewport tag:
    <meta name="viewport" content="width=device-width, initial-scale=1">

    The preceding viewport meta tag specification defines the web page viewport width to follow the device viewport size, as well as scale the page at a ratio of 1:1 upon opening the web page the first time.

  4. Below the viewport meta tag, add the link to the favicon and apple-touch-icon, which will display the website's icon in Apple devices, such as iPhone, iPad, and iPod:
    <link rel="apple-touch-icon" href="assets/img/apple-icon.png">
    <link rel="shortcut icon" href="assets/img/favicon.png" type="image/png">
  5. Add the website's meta description below <title>:
    <meta name="description" content="A simple portoflio website built using Bootstrap">

    The description specified within this meta tag will be displayed in the Search Engine Result Page (SERP).

  6. You may also specify the author of the page with a meta tag below the meta description tag, as follows.
    <meta name="author" content="Thoriq Firdaus">
  7. Inside <body>, add the website off-canvas navigation HTML, as follows:
    <nav id="menu" class="navmenu navmenu-inverse navmenu-fixed-left offcanvas portfolio-menu" role="navigation">
            <ul class="nav navmenu-nav">
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#">Blog</a></li>
                <li><a href="#">Shop</a></li>
                <li><a href="#">Speaking</a></li>
                <li><a href="#">Writing</a></li>
                <li><a href="#">About</a></li>
            </ul>
        </nav>

    Aside from the essential classes that we have mentioned in the Jasny Bootstrap off-canvas section in this chapter, we have also added a new class named portfolio-menu in the <nav> element to apply our very own styles to the off-canvas navigation.

  8. Add the Bootstrap navbar structure, along with <button> to slide the off-canvas in and out:
    <div class="navbar navbar-default navbar-portfolio portfolio-topbar">
    <button type="button" class="navbar-toggle" data-toggle="offcanvas" data-target="#menu" data-canvas="body">
            <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    </button>
    </div>
  9. Below navbar, add the <main> element, as follows:
    <main class="portfolio-main" id="content" role="main">
    </main>

    As described in W3C (http://www.w3.org/TR/html-main-element/), the <main> element defines the main content of the website. So, this is where we will put the website content including the portfolio images.

  10. Add Bootstrap Jumbotron, containing the portfolio website name and a line of catchphrase. Since I will display the work of a friend of mine, Yoga Perdana, I wish to show off his name, along with his catchphrase that is displayed in his Dribbble page profile (https://dribbble.com/yoga), as follows:
    <main class="portfolio-main" id="content" role="main">
    <section class="jumbotron portfolio-about" id="about">
    <h1 class="portfolio-name">Yoga Perdana</h1>
    <p class="lead">Illustrator &amp; Logo designer. I work using digital tools, specially vector.</p>
    </section>
    </main>

    You may freely add your name or company name in this matter.

  11. Below the Bootstrap Jumbotron section, add a new section with the HTML5 <section> element, along with a heading that defines this section, as follows:
    ...
    <section class="jumbotron portfolio-about" id="about">
    <h1 class="portfolio-name">Yoga Perdana</h1>
    <p class="lead">Illustrator &amp; Logo designer. I work using digital tools, specially vector.</p>
    </section>
    <section class="portfolio-display" id="portfolio">
      <h2>Portfolio</h2>
    </section>
  12. Add a Bootstrap container (http://getbootstrap.com/css/#overview-container) below the heading that will contain the portfolio images using the following code:
    <section class="portfolio-display" id="portfolio">
    <h2>Portfolio</h2>
       <div class="container">
    </div>
    </section>
  13. Arrange the portfolio images into columns and rows. We have 12 portfolio images, which means we may have four images/columns in a row. The following is the first row:
    ...
    <div class="container">
    <div class="row">
    <div class="col-md-3 col-sm-6 portfolio-item">
        <figure class="portfolio-image">
    <img class="img-responsive" src="assets/img/6layers.jpg" height="300" width="400" alt="">
    <figcaption class="portfolio-caption">6 Layers</figcaption>
              </figure>
      </div>
    <div class="col-md-3 col-sm-6 portfolio-item">
        <figure class="portfolio-image">
    <img class="img-responsive" src="assets/img/blur.jpg" height="300" width="400" alt="">
    <figcaption class="portfolio-caption">Blur</figcaption>
    </figure>
      </div>
    <div class="col-md-3 col-sm-6 portfolio-item">
              <figure class="portfolio-image">
    <img class="img-responsive" src="assets/img/brain.jpg" height="300" width="400" alt="">
    <figcaption class="portfolio-caption">Brain</figcaption>
    </figure>
      </div>
      <div class="col-md-3 col-sm-6 portfolio-item">
           <figure class="portfolio-image">
    <img class="img-responsive" src="assets/img/color.jpg" height="300" width="400" alt="">
    <figcaption class="portfolio-caption">Color</figcaption>
    </figure>
      </div>
    </div>
    </div>

    Each column is assigned with a special class to allow us to apply customized styles. We also added a class in <figure> that wraps the image, as well as the <figcaption> element that wraps the image caption for the same purpose.

  14. Add the remaining images into columns and rows. Since, in this case, we have 12 images, there should be three rows displayed in the website. Each row contains four images, including one row that we've added in step 13.
  15. Below the portfolio section, add the website message form containing three form fields and a button, as shown in the following code:
    ...
    </section>
    <div class="portfolio-contact" id="contact">
          <div class="container">
            <h2>Get in Touch</h2>
    <form id="contact" method="post" class="form" role="form">
                <div class="form-group">
    <input type="text" class="form-control input-lg" id="input-name" placeholder="Name">
    </div>
                     <div class="form-group">
    <input type="email" class="form-control input-lg" id="input-email" placeholder="Email">
                      </div>
                      <div class="form-group">
    <textarea class="form-control" rows="10"></textarea>
                      </div>
     <button type="submit" class="btn btn-lg btn-primary">Submit</button>
               </form>
    </div>
    </div>
    

    Herein, we made the website form simple with only three form fields. But, you may add extra form fields, as per your own requirement.

  16. Finally, we will add the website footer with the HTML5 <footer> element. The footer, as we have seen from the website wireframe, contains the social media icons and the website copyright statement.
  17. Add the following HTML markup below the website's main content:
    ... 
    </main>
    <footer class="portfolio-footer" id="footer">
            <div class="container">
              <div class="social" id="social">
                <ul>
    <li class="twitter"><a class="icon ion-social-twitter" href="#">Twitter</a></li>
    <li class="dribbble"><a class="icon ion-social-dribbble-outline" href="#">Dribbble</a></li>
                    </ul>
              </div>
    <div class="copyright">Yoga Perdana &copy; 2014</div>
            </div>
        </footer>
What just happened?

We just constructed the portfolio website HTML structure with a couple of HTML5 elements and Have a go hero – extending the portfolio website

Bootstrap ships Pop quiz – Bootstrap button classes

Bootstrap specified a number of reusable classes to quickly shape and form elements with the preset styles.

Q1. Which of the following classes is not used in Bootstrap grid?

col-sm-pull-8
col-md-push-3
col-xs-offset-5
col-lg-6
col-xl-7

Q2. Which of the following classes does Bootstrap use to style a button?

btn-link
btn-submit
btn-send
btn-cancel
btn-enter
 

In the preceding chapter, we constructed the portfolio website structure with HTML5 and a couple of Bootstrap drop-in classes. The website as you might have seen isn't yet decorated. We haven't yet composed our very own styles or linked the style sheet to the page. So, this chapter's focus will be on website decoration.

Bootstrap primarily uses LESS to generate the styles of its components. Following suit, we will also use LESS to style the portfolio website. LESS brings a number of features, such as variables and mixins, that would allow us to write leaner and more efficient style rules. At the end of the day, you will also find customizing and maintaining website styles with LESS is easier than with plain CSS.

Furthermore, we've also used a Bootstrap extension called Jasny Bootstrap to include off-canvas navigation into the portfolio website. At this stage, nothing will happen to the off-canvas navigation; we only set out the HTML structure. So, in this chapter, apart from compiling the website styles, we will also compile the JavaScript library of both Bootstrap and Jasny Bootstrap to make the off-canvas navigation function.

In this chapter, we will discuss many things, including the following topics:

LESS (http://lesscss.org/) is a JavaScript-based CSS preprocessor developed by Alexis Sellier (http://cloudhead.io/), also known as CloudHead. As mentioned, Bootstrap uses LESS to compose its component styles—though it only recently released the Sass version officially. As mentioned, we will follow Bootstrap to use LESS to compose our own style rules and manage style sheets.

In a nutshell, LESS extends CSS by bringing some programming features, such as variable, function, and operation. CSS is a straightforward language and fundamentally very easy to learn. However, maintaining static CSS is practically exhaustive, particularly when we have to deal with a thousand lines of style rules and multiple style sheets. The capabilities that LESS offers, such as variable, mixins, function, and operation (which we are going to take a look at shortly) will allow us to develop style rules that will be easier to maintain and organize.

A variable is the most fundamental feature in LESS. A variable in LESS, as in other programming languages, is used to store a constant or a value that can be reused later limitlessly within the entire style sheet. In LESS, a variable is declared with an @ sign and is followed by the variable name. The variable name can be a combination of numbers and letters. In the following example, we will create a couple of LESS variables to store some colors in the HEX format and assign them in the succeeding style rules to pass the colors, as shown in the following code:

Using a LESS compiler, such as Koala, the preceding codes will be compiled into static CSS, as follows:

Using variables is not only limited to storing colors as we just demonstrated. We can use variables for any type of values, for example:

One of the advantages of using a variable is that, if we have to make a change, we will only need to change the value within the variable. The change we make will take place in every occurrence of that variable in the style sheet. This is certainly a time saver. Scanning through the style sheet and making the change singly or perhaps with the search and replace feature of the code editor might cause unintended changes if not done carefully.

Mixins are one of the most powerful features in LESS. Mixins simplify style rules declaration by allowing us to create a group of CSS properties that can be included in other style rules in the style sheets. Let's take a look at the following code snippet:

In the preceding example, we declared border-radius in three different style rules along with the vendor prefix to cover earlier versions of Firefox- and Webkit-based browsers. In LESS, we are able to simplify border-radius declaration by creating a mixin. A mixin in LESS is simply specified with a class selector. Given the preceding example, let's create a mixin named .border-radius to contain the border-radius properties, as follows:

Afterwards, we include .border-radius into the succeeding style rules to pass the containing properties into them, as follows:

This code will produce exactly the same output as in the first code snippet of this section when compiled into static CSS.

Furthermore, we can also extend the mixins into so-called parametric mixins. This feature allows us to add arguments or variables and turn the mixins to be configurable. Let's take the same example as in the preceding section. But, this time, we will not assign a fixed value; instead, we replace it with a variable, as follows:

Now, we can insert this mixin into other style rules and assign a different value to each:

When we compile it into regular CSS, each style rule is applied with a different border-radius value, as follows:

Extend syntax is the long-awaited feature to come into LESS. One main issue with LESS mixins is that it simply copies the containing CSS properties of a mixin, thus producing duplicate code. Again, if we are dealing with a large-scale website with a thousand lines of codes, the amount of duplicated code would make the style sheet size unnecessarily large.

In Version 1.4, LESS introduced extend syntax. The extend syntax comes in a form that is similar to a CSS pseudo-class, :extend. The extend syntax will group CSS selectors that inherit the properties set containing the mixin. Compare the following two examples.

To begin with, we include a mixin without the :extend syntax:

The preceding LESS code is short, but when it is compiled into CSS, the code extends to around 17 lines, as the border-radius properties are repeated or simply copied in every style rule, as follows:

In this second example, we will put the :extend syntax into practice into the same mixin:

The following is how the code turns into plain CSS; it becomes even shorter than the initial uncompiled LESS codes.

This is one of my favorite features in LESS. The referential import, as the name implies, allows us to import an external style sheet merely as reference. Prior to the emerging of this feature, all style rules in the style sheet imported with the @import directive will be appended, which is more often than not unnecessary.

Since Version 1.5, LESS introduced the (reference) option that marks @import as reference, thus preventing the external style rules from being appended. Add the (reference) mark after @import, as follows:

Perform the following steps to manage the style sheet references:

  1. Go to the project directory and create a new style sheet named var-bootstrap.less in assets/less directory. This style sheet contains the copy of Bootstrap's predefined variables. This copy will allow us to customize the variables without affecting the initial specifications.
  2. Hence, copy the Bootstrap variables in the variables.less style sheet of the /bootstrap/less directory. Paste the complete variables into var-bootstrap.less that we only created in step 1.
  3. Create a new style sheet named var-jasny.less. Similar to var-bootstrap.less, this style sheet will contain the copy of the Jasny Bootstrap variables.
  4. Obtain the Jasny Bootstrap variables in variables.less of the jasny-bootstrap/less directory. Paste all the variables in the var-jasny.less style sheet we just created in step 3.
  5. Create a new style sheet named frameworks.less.
  6. We are going to use this style sheet to import the Bootstrap and Jasny Bootstrap style sheets residing in the bower_component folder.
  7. In frameworks.less, create a variable named @path-bootstrap to define the path, pointing to the folder named less, where all the LESS style sheets of Bootstrap reside:
    @path-bootstrap: '../../bower_components/bootstrap/less/';
  8. Similarly, create a variable that defines the path, pointing to the Jasny Bootstrap less folder, as follows:
    @path-jasny: '../../bower_components/jasny-bootstrap/less/';
  9. Also create one to define the Ionicons path:
    @path-ionicons: '../../bower_components/ionicons-less/less/';
  10. Import the style sheets that contain variables using the following code:
    @import 'var-bootstrap.less';
    @import 'var-jasny.less';
  11. Import the Bootstrap and Jasny Bootstrap style sheets, which are only required to build the portfolio website. Specify the paths using the variables we created in steps 6 to 8, as follows:
    // Mixins
    @import '@{path-bootstrap}mixins.less';
    
    // Reset
    @import '@{path-bootstrap}normalize.less';
    @import '@{path-bootstrap}print.less';
    
    // Core CSS
    @import '@{path-bootstrap}scaffolding.less';
    @import '@{path-bootstrap}type.less';
    @import '@{path-bootstrap}grid.less';
    @import '@{path-bootstrap}forms.less';
    @import '@{path-bootstrap}buttons.less';
    
    // Icons 
    @import '@{path-ionicons}ionicons.less';
    
    // Components
    @import '@{path-bootstrap}navs.less';
    @import '@{path-bootstrap}navbar.less';
    @import '@{path-bootstrap}jumbotron.less';
    
    // Offcanvas
    @import "@{path-jasny}navmenu.less";
    @import "@{path-jasny}offcanvas.less";
    
    // Utility classes
    @import '@{path-bootstrap}utilities.less';
    @import '@{path-bootstrap}responsive-utilities.less';
  12. Create a new style sheet named style.less. This is the style sheet where we are going to compose our very own style rules.
  13. Import the Bootstrap variables and the mixins within style.less:
    @path-bootstrap: '../../bower_components/bootstrap/less/'; 
    @import 'var-bootstrap.less';
    @import 'var-jasny.less'; 
    @import (reference) '@{path-bootstrap}mixins.less';
What just happened?

To sum up, we just created style sheets and put them in order. At first, we created two style sheets named var-bootstrap.less and var-jasny.less to store the Bootstrap and Jasny Bootstrap variables. As mentioned, we made these copies to avoid directly altering the originals. We have also created a style sheet named frameworks.less, containing references to the Bootstrap and Jasny Bootstrap style sheets.

Finally, we created the website primary style sheet named style.less and imported the variables and mixins so that they are reusable inside the style.less. Have a go hero – name and organize the style sheets

In the Pop quiz – which of the following option is not LESS Import option?

Q1. In one of the section of this chapter, we discussed (reference), which imports yet treats external LESS style sheets only as a reference. In addition to (reference), LESS also provides more options to import a style sheet. So, which of the following is not the LESS import option?

(less)
(css)
(multiple)
(once)
(default)

Q2. How do you use variable within an @import statement?

@import '@{variable}style.less';
@import '@[variable]style.less';
@import '@(variable)style.less';

Perform the following steps to compile LESS into CSS using Koala:

What just happened?

In the preceding steps, we compiled the website primary style sheets, frameworks.less and style.less, from LESS to CSS. You should now have them along with the source maps in the assets/css/ directory. The code is compressed, thus resulting in a relatively small file size, as shown in the following screenshot:

What just happened?

The style sheets are relatively small in size. As shown, frameworks.css is 92 kb, while style.css is only 2 kb

Additionally, we

Perform the following steps to style the website:

  1. Add a new font family from Google Font. Herein, I opted for Varela Round (http://www.google.com/fonts/specimen/Varela+Round). Place the following Google Font link before any other style sheets:
    <link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  2. We will customize the default styles by changing some variables. Open var-bootstrap.less in Sublime Text. First, we change the @brand-primary variable that defines the Bootstrap primary color; change it from #428bca to #46acb8:
    Time for action – composing the website styles with LESS syntax
  3. Also, change the color in the @brand-success variable from #5cb85c to #7ba47c:
    Time for action – composing the website styles with LESS syntax
  4. Change the @headings-font-family variable, which defines the font family used in the headings, from inherit to "Varela Round", as follows:
    @headings-font-family: "Varela Round", @font-family-sans-serif; 
  5. The Bootstrap default style shows a glowing effect when the user focusses on a form field. The color of this effect is specified in @input-border-focus. Change the color from #66afe9 to #89c6cb:
    Time for action – composing the website styles with LESS syntax
  6. In the top section of the website, you can see that the navbar still has the Bootstrap default style with the gray background and border color, as shown in the following screenshot:
    Time for action – composing the website styles with LESS syntax
  7. These two colors are specified in @navbar-default-bg and @navbar-default-border, respectively. Change both of these variable values to transparent, as follows:
    @navbar-default-bg: transparent;
    @navbar-default-border: transparent;
  8. Similarly, the default style of the Jumbotron section is set with a gray background color. To remove this color, set the @jumbotron-bg variable to transparent, as follows:
    @jumbotron-bg: transparent;
  9. We will be back editing a few more Bootstrap variables later on. For the meantime, let's write our own style rules. To begin with, we will show the navbar toggle button, which is hidden by the Bootstrap default styles. In our case, this button will be used to slide the off-canvas navigation on and off. Let's force this button to be visible with the following style rules:
    .portfolio-topbar {
      .navbar-toggle {
        display: block;
      }
    }
  10. As you can see from the following screenshot, the toggle button with the so-called hamburger icon (http://gizmodo.com/who-designed-the-iconic-hamburger-icon-1555438787) is now visible:
    Time for action – composing the website styles with LESS syntax
  11. Currently, this button is positioned on the right-hand side. Referring to the website blueprint, it should be on the left. Add float:left to put it on the left-hand side and margin-left:15px to add a little whitespace to the button's left, as follows:
    .portfolio-topbar {
      .navbar-toggle {
        display: block;
        float: left;
        margin-left: 15px;
      }
    } 
  12. Herein, I want to customize the toggle button's default styles, which are also specified through a couple of variables in var-bootstrap.less. Hence, open var-bootstrap.less in Sublime Text.
  13. First of all, we will remove the button borders by changing the value of the @navbar-default-toggle-border-color variable from #ddd to transparent, as follows:
    @navbar-default-toggle-border-color: transparent;
  14. We will also remove the gray background color that appears when we hover over the button. Remove the gray background color out of it by changing the @navbar-default-toggle-hover-bg variable from #ddd to transparent, as follows:
    @navbar-default-toggle-hover-bg: transparent;
  15. I want the hamburger icon to look bolder and strong. So, herein, we want to change the colors to black. Change the value of @navbar-default-toggle-icon-bar-bg from #888 to #000:
     @navbar-default-toggle-icon-bar-bg: #000;
  16. At this stage, the website content is aligned to the left-hand side, which is the default browser alignment for any content. Following the website blueprint, the website content should be centered. Use text-align: center, as follows, to align the content to the center:
    .portfolio-about,
    .portfolio-display,
    .portfolio-contact,
    .portfolio-footer {
      text-align: center;
    }
  17. Add the following to turn the website name to all-caps (all capital letters), making it bigger and bolder:
    .portfolio-about {
      .portfolio-name {
        text-transform: uppercase;
      }
    }
  18. On the other hand, make the catchphrase line subtler by specifying the text color to gray light. Herein, we can simply use Bootstrap's predefined variable named @gray-light to apply the gray color, as follows:
    .portfolio-about {
      .portfolio-name {
        text-transform: uppercase;
      }
      .lead {
        color: @gray-light;
      }
    }
  19. In the portfolio section, specify the background color with gray light, which is lighter than the color in @gray-lighter variable. The addition of the background color aims to lay a bit of emphasis on the portfolio section.
  20. In this project, we opt to use the LESS darken() function to slightly darken the white color, as follows:
    .portfolio-display {
      background-color: darken(#fff, 1%);
    }
  21. At this stage, if we take a look at the portfolio section, it seems there are merely little spaces at the top and the bottom, as pointed out in the following screenshot:
    Time for action – composing the website styles with LESS syntax
  22. Give the portfolio section more space to breathe at the top and bottom by adding padding-top and padding-bottom, as follows:
    .portfolio-display {
      background-color: darken(#fff, 1%);
    padding-top: 60px;
      padding-bottom: 60px;
    }
  23. To sum up, we added two headings in the website, including one in the portfolio section, to explicitly display the section name. These headings will share the same style rules. So, in that case, we better create a mixin that specifically defines the heading styles.
  24. Define the mixin as well as the CSS properties to apply the heading styles, as follows:
    .heading {
      color: lighten(#000, 70%);  
      text-transform: uppercase;
      font-size: 21px;
      margin-bottom: 60px;  
    }
  25. Add the following style rules for the section heading, which will make it look subtler and in tune with the background color of the portfolio section:
    .portfolio-display {
    ...
      h2 {
        &:extend(.heading);
      }
    }
  26. As shown in the following screenshot, there is only very little space in between each row; the rows are too close to each other, as follows:
    Time for action – composing the website styles with LESS syntax

    So, put more space by specifying margin-bottom for each portfolio item, as follows:

    .portfolio-item {
      margin-bottom: 30px;
    }
  27. Add styles for the portfolio image, as follows:
    .portfolio-image {
      padding: 15px;
      background-color: #fff;
    margin-right: auto;
    margin-left: auto;
    }
  28. Also, add the styles for the caption, as follows:
    .portfolio-caption {
      font-weight: 500;
      margin-top: 15px;
      color: @gray;
    }
  29. What do you think about showing a transition effect when we hover over the portfolio image? That will look nice, won't it? In this case, I would like to show a shadow surrounding the portfolio image upon hover.
  30. Add the effect using Bootstrap's predefined mixins,.transition() and .box-shadow(), as follows:
    .portfolio-image {
      padding: 15px;
      background-color: #fff;
    margin-right: auto;
    margin-left: auto; 
      .transition(box-shadow 1s);
      &:hover {
        .box-shadow(0 0 8px fade(#000, 10%));
      }
    }
  31. Below the portfolio section, we have the website contact form, which has already been applied with the Bootstrap default styling. So, let's customize it with our own style rules.
  32. First, we will add more spaces at the top and the bottom of the contact form section with padding.
  33. Add the styles for the heading with the .heading mixin we created in step 18:
    .portfolio-contact {
    ...
      h2 {
        &:extend(.heading);
      }
    } 
  34. The form currently spans the container fully. So, add the following style rules to set the maximum width, yet still display the form in the middle of the container, as follows:
    .portfolio-contact {
    ...
      .form {
        width: 100%;
        max-width: 600px;
        margin-right: auto;
        margin-left: auto;
      }
    } 
  35. Add the following style rules to make the form elements—<input>, <textarea>, <button>—look flatter. These style rules remove the shadow and lower the border radius. Have a look at the following code:
    .portfolio-contact {
    ...
      .form {
        width: 100%;
        max-width: 600px;
        margin-right: auto;
        margin-left: auto;
        input, textarea, button {
          box-shadow: none;
          border-radius: @border-radius-small;
        }
      }
    }
  36. Add the following lines to style the button and make it live with a transition effect, as follows:
    .portfolio-contact {
    ...
      .form {
        width: 100%;
        max-width: 600px;
        margin-right: auto;
        margin-left: auto;
        input, textarea, button {
          box-shadow: none;
          border-radius: @border-radius-small;
        }
        .btn {
          display: block;
          width: 100%;
          .transition(background-color 500ms);
        }
      }
    }
  37. Starting this step, we will add style rules for the footer, the last section of the website. The footer contains the social media links, Dribbble and Twitter, and a copyright statement at the very bottom.
  38. First, as in the preceding sections, we put more whitespace at the top and bottom of the section with padding:
    .portfolio-footer {
      padding-top: 60px;
      padding-bottom: 60px;
    }
  39. Then, we put more spaces between the social media links and the copyright statement with margin-bottom:
    .portfolio-footer {
      padding-top: 60px;
      padding-bottom: 60px;
    .social {
        margin-bottom: 30px;
    }
    } 
  40. Add the following lines to remove the <ul> element padding derived from default browser styles:
    .portfolio-footer {
    ...
      .social {
        margin-bottom: 30px;
        ul {
          padding-left: 0;
        }
      }
    }
  41. Add the highlighted lines in the following code to display the social media links beside each other:
    .portfolio-footer {
    ...
      .social {
        margin-bottom: 30px;
        ul {
          padding-left: 0;
        }
        li {
          list-style: none;
          display: inline-block;
          margin: 0 15px;
        }
      }
    }
  42. Give the social media links the color of their respective social media brands, as follows:
    .portfolio-footer {
    ...
      .social {
        ...
        a {
          font-weight: 600;
          color: @gray;
          text-decoration: none;
          .transition(color 500ms);
          &:before {
            display: block;
            font-size: 32px;
            margin-bottom: 5px;
          }
        }
        .twitter a:hover {
          color: #55acee;
        }
        .dribbble a:hover {
          color: #ea4c89;
        }
      }
    } 
  43. Finally, make the copyright statement color subtler with the gray color:
    .portfolio-footer {
    ...
      .copyright {
        color: @gray-light;
      }
    }
What just happened?

In the preceding steps, we just styled the website by customizing a number of Bootstrap variables as well as composing our own style rules. Compile style.less to generate the CSS. Additionally, you can obtain all the style rules we applied from this Gist ( Have a go hero – being more creative

Many of the style rules that we have just applied in the preceding section are merely decorative. Feel free to add more creativity and customization, as follows:

Explore Pop quiz — using LESS function and extend syntax

Q1. How do you make a color lighter with LESS?

lighter(#000, 30%);
lighten(#000, 30%);
lightening(#000, 30%);

Q2. How do you make a color transparent?

fadeout(#000, 10%);
transparentize(#000, 10%);
fade-out(#000, 10%);

Q3. Which one of the following is an incorrect way to extend a mixin in LESS?

.class:extend(.another-class);
.class::extend(.another-class);
.class {

:extend(.another-class);

}

  1. Create a new JavaScript file named html5shiv.js in assets/js directory.
  2. Import html5shiv.js from the HTML5Shiv package we downloaded through Bower into this file:
    // @koala-prepend "../../bower_components/html5shiv/dist/html5shiv.js"
  3. Create a new JavaScript file named bootstrap.js.
  4. In bootstrap.js, import the JavaScript libraries that are required to turn the off-canvas navigation functionality on, as follows:
    // @koala-prepend "../../bower_components/jquery/dist/jquery.js"
    // @koala-prepend "../../bower_components/bootstrap/js/transition.js"
    // @koala-prepend "../../bower_components/jasny-bootstrap/js/offcanvas.js"
  5. Open Koala and ensure that the Auto Compile option for html5shiv.js and bootstrap.js is checked, as shown in the following screenshot:
    Time for action – compiling JavaScript with Koala
  6. Also, make sure that the output path of these two JavaScript files is set to the /assets/js directory, as shown in the following screenshot:
    Time for action – compiling JavaScript with Koala
  7. Compile both these JavaScript files by clicking on the Compile button in Koala, as follows:
    Time for action – compiling JavaScript with Koala

    Once these JavaScript files are compiled, you should find the minified version of these files, html5shiv.min.js and bootstrap.min.js, as shown in the following screenshot:

    Time for action – compiling JavaScript with Koala
  8. Open index.html in Sublime Text, and link html5shiv.js within the <head> section using the Internet Explorer conditional comment tag, as follows:
    <!--[if lt IE 9]>
    <script type="text/javascript" src="assets/js/html5shiv.min.js"></script>
    <![endif]-->
  9. Link bootstrap.min.js at the bottom of index.html, as follows:
    <script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
What just happened?

We just compiled jQuery and Bootstrap JavaScript libraries to enable the off-canvas functionality. We also enabled HTML5 elements in Internet Explorer 8 using HTML5Shiv. By now, the website is fully functional.
 

In this era, where many people are connected to the Internet, having a website becomes an essential for a company of any size—a small company or a Fortune 500 company with multibillion businesses. Therefore, in this third project of this module, we are going to build a responsive website for business.

To build the website, we will adopt a new framework called Foundation. Foundation is built by ZURB, a web-development agency based in California. It's a meticulously crafted framework with a stack of interactive widgets. On the technical side, Foundation styles are built on top of Sass and SCSS. Hence, we will also walk through the subject during the course of working on the project.

To work towards this project, first let's assume that you have a business idea. It might be a bit exaggerated, but it's a brilliant idea that could potentially turn into a multibillion-dollar business and change the world. You have an awesome product baked, and now it's time to build the website. You are very excited and cannot wait to rock the world.

So, without further ado, let's get the project started.

This chapter will primarily revolve around Foundation, and the topics that we are going to cover herein include:

First and foremost, unlike the previous two projects we did, we are going to examine the website layout in wireframe before going any further in the chapter. After examining it, we will discover the Foundation components that are required for the website, along with the components and assets that may not be available in the Foundation package. The following is the website layout in the normal desktop screen size:

Examining the website layout

The preceding wireframe shows that the website will have five sections. The first section, plainly, is the header. The header section will contain the website logo, menu navigation, a few lines of catchphrases, and a button—many call it a call-to-action button.

Normally, people need to get as much information as they can about the advantages and disadvantages before deciding to buy. So, under the header, we will display the list of items of the product or the key features offered.

In addition to the features list, we will also display customer testimonials within a slider. According to www.entrepreneur.com (http://www.entrepreneur.com/article/83752), displaying customer testimonials is one of the effective ways to drive more customers or sales, which is eventually good for business.

Below the testimonial section, the website will display the plan and price tables. And the last section will be the footer, containing secondary website navigation and links to Facebook and Twitter.

Let's now see how the website's layout will be in a smaller viewport size, which is as follows:

Examining the website layout

Much like the websites we built in the previous projects, all the content will be stacked. The catchphrases and the call-to-action button are aligned to the center. The menu in the navigation is now depicted as the hamburger icon. Next, we will see what Foundation has to offer in its package to build the website.

Foundation (http://foundation.zurb.com/) is one of the most popular frontend development frameworks. It is used by a number of notable companies, such as Pixar, Washington Post, Warby Parker (https://www.warbyparker.com/), and so on. As mentioned, Foundation ships with common web components and interactive widgets. Herein, we will look into the components, as well as the widgets we are going to employ for the website.

The grid system is an integral part of a framework. It is one thing that makes managing web layout feel like a breeze. Foundation's grid system comprises twelve columns that can adapt to narrow viewport size through the drop-in classes provided. Similar to both the frameworks we explored in the previous chapters, the grid consists of rows and columns. Every column has to be wrapped within a row for the layout to span properly.

In Foundation, apply the row class to define an element as a row, and apply the element with the columns or column class to define it as a column. For example:

You may also omit the s from columns, as follows:

The column size is defined through the following series of classes:

These classes can be applied in conjunction within a single element. For example:

The preceding example gives the following result in the browser:

The grid system

Resize the viewport size such that it is small enough and that the columns' width shifts following the assigned classes. In this case, each column has an equal width since both of them are assigned with the small-6 class:

The grid system

One of the important sections on a website is the navigation. The navigation helps users to browse the website from one page to another. Foundation, in this case, provides a couple of navigation types, and among them, one is called the top bar. Foundation's top bar will reside at the very top of the website before any content or section. The following is how the top bar will appear with the Foundation default style:

The navigation and top bar

The top bar is responsive. Try resizing the browser's viewport size such that it is small enough, and you will find that the navigation is concealed within the menu, which requires us to click on MENU to reveal the full list of the menu items:

The navigation and top bar

The Foundation top bar is primarily formed with the top-bar class to apply the styles, the data-topbar attribute to run the JavaScript function related to the top bar, and finally role="navigation" for better accessibility.

So, the following code is how we start to build the top bar in Foundation:

Foundation splits the top bar content into two sections. The left-hand side area is called the title area, consisting of the website name or logo. Foundation constructs this section with the list element, as follows:

The second section is simply called the top bar section. Typically, this section contains the menu, buttons, and search form. Foundation sets this section using the top-bar-section class, along with the left and right class to specify the alignment. So, to put it all together, the following is the complete code to build a basic Foundation top bar, as you see in the preceding screenshots:

Certainly, you will have to link the Foundation CSS style sheet beforehand in the document to see the top bar look.

The carousel or slider is one of the most popular design patterns on the web. Despite the debate with respect to its accessibility, many people still love to have it on their website—and so do we. Herein, we want to employ Orbit (http://foundation.zurb.com/docs/components/orbit.html), the Foundation jQuery plugin to display a content slider.

Orbit is customizable in that we can fully control the output, as well as the behavior of the slide through classes, attributes, or JavaScript initiation. We can also add almost anything within the Orbit slides, including textual content, images, links, and the mix. And needless to say, we can style most of its parts.

The grid system

The grid system is an integral part of a framework. It is one thing that makes managing web layout feel like a breeze. Foundation's grid system comprises twelve columns that can adapt to narrow

viewport size through the drop-in classes provided. Similar to both the frameworks we explored in the previous chapters, the grid consists of rows and columns. Every column has to be wrapped within a row for the layout to span properly.

In Foundation, apply the row class to define an element as a row, and apply the element with the columns or column class to define it as a column. For example:

You may also omit the s from columns, as follows:

The column size is defined through the following series of classes:

These classes can be applied in conjunction within a single element. For example:

The preceding example gives the following result in the browser:

The grid system

Resize the viewport size such that it is small enough and that the columns' width shifts following the assigned classes. In this case, each column has an equal width since both of them are assigned with the small-6 class:

The grid system

One of the important sections on a website is the navigation. The navigation helps users to browse the website from one page to another. Foundation, in this case, provides a couple of navigation types, and among them, one is called the top bar. Foundation's top bar will reside at the very top of the website before any content or section. The following is how the top bar will appear with the Foundation default style:

The navigation and top bar

The top bar is responsive. Try resizing the browser's viewport size such that it is small enough, and you will find that the navigation is concealed within the menu, which requires us to click on MENU to reveal the full list of the menu items:

The navigation and top bar

The Foundation top bar is primarily formed with the top-bar class to apply the styles, the data-topbar attribute to run the JavaScript function related to the top bar, and finally role="navigation" for better accessibility.

So, the following code is how we start to build the top bar in Foundation:

Foundation splits the top bar content into two sections. The left-hand side area is called the title area, consisting of the website name or logo. Foundation constructs this section with the list element, as follows:

The second section is simply called the top bar section. Typically, this section contains the menu, buttons, and search form. Foundation sets this section using the top-bar-section class, along with the left and right class to specify the alignment. So, to put it all together, the following is the complete code to build a basic Foundation top bar, as you see in the preceding screenshots:

Certainly, you will have to link the Foundation CSS style sheet beforehand in the document to see the top bar look.

The carousel or slider is one of the most popular design patterns on the web. Despite the debate with respect to its accessibility, many people still love to have it on their website—and so do we. Herein, we want to employ Orbit (http://foundation.zurb.com/docs/components/orbit.html), the Foundation jQuery plugin to display a content slider.

Orbit is customizable in that we can fully control the output, as well as the behavior of the slide through classes, attributes, or JavaScript initiation. We can also add almost anything within the Orbit slides, including textual content, images, links, and the mix. And needless to say, we can style most of its parts.

The buttons

The button is

One of the important sections on a website is the navigation. The navigation helps users to browse the website from one page to another. Foundation, in this case, provides a couple of navigation types, and among them, one is called the top bar. Foundation's top bar will reside at the very top of the website before any content or section. The following is how the top bar will appear with the Foundation default style:

The navigation and top bar

The top bar is responsive. Try resizing the browser's viewport size such that it is small enough, and you will find that the navigation is concealed within the menu, which requires us to click on MENU to reveal the full list of the menu items:

The navigation and top bar

The Foundation top bar is primarily formed with the top-bar class to apply the styles, the data-topbar attribute to run the JavaScript function related to the top bar, and finally role="navigation" for better accessibility.

So, the following code is how we start to build the top bar in Foundation:

Foundation splits the top bar content into two sections. The left-hand side area is called the title area, consisting of the website name or logo. Foundation constructs this section with the list element, as follows:

The second section is simply called the top bar section. Typically, this section contains the menu, buttons, and search form. Foundation sets this section using the top-bar-section class, along with the left and right class to specify the alignment. So, to put it all together, the following is the complete code to build a basic Foundation top bar, as you see in the preceding screenshots:

Certainly, you will have to link the Foundation CSS style sheet beforehand in the document to see the top bar look.

The carousel or slider is one of the most popular design patterns on the web. Despite the debate with respect to its accessibility, many people still love to have it on their website—and so do we. Herein, we want to employ Orbit (http://foundation.zurb.com/docs/components/orbit.html), the Foundation jQuery plugin to display a content slider.

Orbit is customizable in that we can fully control the output, as well as the behavior of the slide through classes, attributes, or JavaScript initiation. We can also add almost anything within the Orbit slides, including textual content, images, links, and the mix. And needless to say, we can style most of its parts.

The navigation and top bar

One of the important

sections on a website is the navigation. The navigation helps users to browse the website from one page to another. Foundation, in this case, provides a couple of navigation types, and among them, one is called the top bar. Foundation's top bar will reside at the very top of the website before any content or section. The following is how the top bar will appear with the Foundation default style:

The navigation and top bar

The top bar is responsive. Try resizing the browser's viewport size such that it is small enough, and you will find that the navigation is concealed within the menu, which requires us to click on MENU to reveal the full list of the menu items:

The navigation and top bar

The Foundation top bar is primarily formed with the top-bar class to apply the styles, the data-topbar attribute to run the JavaScript function related to the top bar, and finally role="navigation" for better accessibility.

So, the following code is how we start to build the top bar in Foundation:

Foundation splits the top bar content into two sections. The left-hand side area is called the title area, consisting of the website name or logo. Foundation constructs this section with the list element, as follows:

The second section is simply called the top bar section. Typically, this section contains the menu, buttons, and search form. Foundation sets this section using the top-bar-section class, along with the left and right class to specify the alignment. So, to put it all together, the following is the complete code to build a basic Foundation top bar, as you see in the preceding screenshots:

Certainly, you will have to link the Foundation CSS style sheet beforehand in the document to see the top bar look.

The carousel or slider is one of the most popular design patterns on the web. Despite the debate with respect to its accessibility, many people still love to have it on their website—and so do we. Herein, we want to employ Orbit (http://foundation.zurb.com/docs/components/orbit.html), the Foundation jQuery plugin to display a content slider.

Orbit is customizable in that we can fully control the output, as well as the behavior of the slide through classes, attributes, or JavaScript initiation. We can also add almost anything within the Orbit slides, including textual content, images, links, and the mix. And needless to say, we can style most of its parts.

The pricing tables

Whether you are selling products or services, you should name your price.

As we will build a website for business, we will need to display pricing tables. Fortunately, Foundation

The carousel or slider is one of the most popular design patterns on the web. Despite the debate with respect to its accessibility, many people still love to have it on their website—and so do we. Herein, we want to employ Orbit (http://foundation.zurb.com/docs/components/orbit.html), the Foundation jQuery plugin to display a content slider.

Orbit is customizable in that we can fully control the output, as well as the behavior of the slide through classes, attributes, or JavaScript initiation. We can also add almost anything within the Orbit slides, including textual content, images, links, and the mix. And needless to say, we can style most of its parts.

Moving around Orbit

The carousel or

slider is one of the most popular design patterns on the web. Despite the debate with respect to its accessibility, many people still love to have it on their website—and so do we. Herein, we want to employ Orbit (http://foundation.zurb.com/docs/components/orbit.html), the Foundation jQuery plugin to display a content slider.

Orbit is customizable in that we can fully control the output, as well as the behavior of the slide through classes, attributes, or JavaScript initiation. We can also add almost anything within the Orbit slides, including textual content, images, links, and the mix. And needless to say, we can style most of its parts.

How is Orbit constructed?

Foundation uses the list element to construct the slide container, as well as the slides, and initiates the functionality
Adding add-ons, the font Icons

Foundation also Further on Foundation

Detailing every corner and

There are several files that we will need in addition to Foundation's own components. These files encompass the image cover for the website header, the icons that will represent the feature in the website feature list section, the favicon image as well as the Apple icons, the avatar image to display in the testimonial section, and finally (which is also important) the website logo.

In terms of the header image, we will use the following image photographed by Alejandro Escamilla, which shows a man working with his Macbook Air; the screen seems off though (http://unsplash.com/post/51493972685/download-by-alejandro-escamilla):

Additional required assets

The icons to display alongside the feature list items are designed by Nick Frost from Ballicons (http://ballicons.net/). Among the icons in the collection that we will include in the website are the following:

Additional required assets

The following are the favicon and the Apple icon, which are generated using a Photoshop action called AppIconTemplate (http://appicontemplate.com/):

Additional required assets

Favicon and the Apple icon

We will use the mystery man of WordPress as the default avatar. This avatar image will be displayed above the testimonial lines, as shown in the following wireframe:

Additional required assets

The mystery man

The logo of this website is made with SVG for the sake of clarity and scalability. The logo is shown in the following screenshot:

Additional required assets

You can get all these assets from the source files that come along with this module. Otherwise, grab them from the URL that we showed in the preceding paragraphs.

  1. In the htdocs folder, create a new folder, and name it startup. This is the folder in which the website will live.
  2. Within the startup folder, create a folder named assets to contain all the assets like the style sheets, JavaScripts, images, and others.
  3. Inside the assets folder create folders to group these assets:
    • css for the style sheets.
    • js to contain the JavaScripts.
    • scss to contain SCSS style sheet (more about SCSS in the next chapter).
    • img to contain the images.
    • fonts to contain the font icons.
  4. Add the images, including the website logo, header image, icons, and the avatar image, as shown in the following screenshot:
    Time for action – organizing the project directories, assets, and dependencies
  5. Now, we will download the project dependencies, which will include the Foundation framework, the icons, jQuery, and a couple of other libraries. Hence, let's open a terminal or command prompt if you are using Windows. Then, navigate to the project directory with the cd command:
    • In Windows: cd \xampp\htdocs\startup
    • In OSX: cd /Applications/XAMPP/htdocs/startup
    • In Ubuntu: cd /opt/lampp/htdocs/startup
  6. As we did in the second project, type the command, fill out the prompts to set the project specification, including the project name and the project version, as shown in the following screenshot:
    Time for action – organizing the project directories, assets, and dependencies

    When all the prompts are filled and completed, Bower will generate a new file named bower.json to put all the information in.

  7. Before we install the project dependencies, we will set the dependencies folder destination. To do so, create a dot file named .bowerrc. Save the file with the following lines in it:
    {
      "directory": "components"
    }

    This line will tell Bower to name the folder components instead of bower_components. And once the configuration is set, we are ready to install the libraries, starting with installing the Foundation package.

  8. To install the Foundation package through Bower, type bower install foundation ––save. Make sure that the --save parameter is included to record Foundation within the bower.json file.
  9. The Foundation font icon is set in a separate repository. To install it, type the bower install foundation-icons --save command.
  10. The Foundation icon package comes with the style sheet that specifies and presents the icon through HTML classes and also the icon files. Herein, we need to make a copy of the font from the package folder into our own fonts folder. Have a look at the following screenshot:
    Time for action – organizing the project directories, assets, and dependencies
What just happened?

We just created the project directory, as well as folders to organize the project assets. In addition, we also installed the libraries that are required to build the website through Bower, which include the Foundation framework.

Having added in the images and the libraries, we will build the website's home page markup in the next section. So, without further ado, let's move on, and it's time for action again.

  1. Create a new HTML file named index.html. Then, open it in Sublime Text, our code editor of choice In this module.
  2. Let's add the basic HTML5 structure as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Startup</title>
    </head>
    <body>
      
    </body>
    </html>
  3. Add the meta X-UA-Compatible variable with the content value IE=edge to allow Internet Explorer to use its latest cutting-edge rendering version:
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
  4. Not to forget the meta viewport tag required to make the website responsive; add it in <head> as follows:
    <meta name="viewport" content="width=device-width, initial-scale=1">
  5. Add the favicon, as well as the Apple icon, below the meta viewport tag, as follows:
    <link rel="apple-touch-icon" href="assets/img/apple-icon.png">
    <link rel="shortcut icon" href="assets/img/favicon.png" type="image/png">
  6. Add the meta description for the search engine result purposes:
    <meta name="description" content="A startup company website built using Foundation">
  7. The HTML markup for the content will follow the Foundation guidelines, as we have discussed in the early sections of this module. In addition, we may add extra classes in the elements to customize the styles. Let's start off by adding the website <header>, for which, add the following lines within <body>:
    <header class="startup-header">
    ...
    </header>
  8. Next, add the website navigation bar within the header, as follows:
    <header class="startup-header">
    <div class="contain-to-grid startup-top-bar">
    <nav class="top-bar" data-topbar>
         <ul class="title-area">
               <li class="name startup-name">
                     <h1><a href="#">Startup</a></h1>
                   </li>
    <li class="toggle-topbar menu-icon">
                     <a href="#"><span>Menu</span></a>
    </li>
    </ul>
             <section class="top-bar-section">
               <ul class="right">
                     <li><a href="#">Features</a></li>
    <li><a href="#">Pricing</a></li>
    <li><a href="#">Blog</a></li>
    <li class="has-form log-in"><a href="" class="button secondary round">Log In</a></li>
    <li class="has-form sign-up"><a href="#" class="button round">Sign Up</a></li>
                   </ul>
    </section>
    </nav>
    </div>
    </header>
  9. Below the navigation bar HTML markup, we add the catchphrase and call-to-action button, as follows:
    <header class="startup-header"> 
      ...
    <div class="panel startup-hero">
           <div class="row">
    <h2 class="hero-title">Stay Cool and be Awesome</h2>
    <p class="hero-lead">The most awesome web application in the galaxy.</p>
    </div>
           <div class="row">
    <a href="#" class="button success round">Signup</a>
           </div>
    </div>
    </header>
  10. Next, we will add the website's body content that will contain the product feature list section, the testimonial section, and the plan table price. First, add a <div> that will wrap the body content sections below the header, as follows:
    <div class="startup-body">
      ...
    </div>
  11. Within <div>, we add the HTML markup for the feature list section, as follows:
    <div class="startup-body">
    <div class="startup-features">
    <div class="row">
         <div class="medium-6 columns">
               <div class="row">
                   <div class="small-3 medium-4 columns">
                   <figure>
    <img src="assets/img/analytics.png" height="128" width="128" alt="">
                   </figure>
    </div>
             <div class="small-9 medium-8 columns">
               <h4>Easy</h4>
    <p>This web application is super easy to use. No complicated setup. It just works out of the box.</p>
     </div>
              </div>
              </div>
              <div class="medium-6 columns">
                <div class="row">
    <div class="small-3 medium-4 columns">
                         <figure>
                        <img src="assets/img/clock.png" height="128" width="128" alt="">
                        </figure>
                            </div>
                            <div class="small-9 medium-8 columns">
                                <h4>Fast</h4>
                                <p>This web application runs in a blink of eye. There is no other application that is on par with our application in term of speed.</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="medium-6 columns">
                        <div class="row">
    <div class="small-3 medium-4 columns">
                             <figure>
    <img src="assets/img/target.png" height="128" width="128" alt="">
    </figure>
                            </div>
    <div class="small-9 medium-8 columns">
        <h4>Secure</h4>
    <p>Your data is encyrpted with the latest Kryptonian technology. It will never be shared to anyone. Rest assured, your data is totally safe.</p>
                            </div>
                        </div>
                    </div>
                    <div class="medium-6 columns">
                        <div class="row">
                            <div class="small-3 medium-4 columns">
                                <figure>
                                    <img src="assets/img/bubbles.png" height="128" width="128" alt="">
                                </figure>
                            </div>
                            <div class="small-9 medium-8 columns">
                                <h4>Awesome</h4>
                                <p>It's simply the most awesome web application and make you the coolest person in the galaxy. Enough said.</p>
                            </div>
    </div>
                </div>
           </div>
    </div>
    </div> 

    The column division for this section refers to the layout shown in the website wireframe. So, as you can see from the preceding code that we just added, each feature list item is assigned with medium-6 columns, hence the column width of each item will be equal.

  12. Below the feature list section, we add the testimonial section's HTML markup, as follows:
    <div class="startup-body">
    ...
    <div class="startup-testimonial">
                <div class="row">
                    <ul class="testimonial-list" data-orbit>
                        <li data-orbit-slide="testimonial-1">
                            <div>
                                <blockquote>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor numquam quaerat doloremque in quis dolore enim modi cumque eligendi eius.</blockquote>
                                <figure>
                                    <img class="avatar" src="assets/img/mystery.png" height="128" width="128" alt="">
                                    <figcaption>John Doe</figcaption>
                                </figure>
                            </div>
                        </li>
                        <li data-orbit-slide="testimonial-2">
                            <div>
                                <blockquote>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</blockquote>
                                <figure>
                                    <img class="avatar" src="assets/img/mystery.png" height="128" width="128" alt="">
                                    <figcaption>Jane Doe</figcaption>
                                </figure>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
    </div>
  13. Referring to the layout in the wireframe, we should add the plan price table below the testimonial section, as follows:
    <div class="startup-body">
    <!-- ... feature list section … -->
    <!-- ... testimonial section … --> 
    <div class="startup-pricing">
                <div class="row">
                    <div class="medium-4 columns">
                        <ul class="pricing-table pricing-basic">
                            <li class="title">Basic</li>
                            <li class="price">$10<small>/month</small></li>
                            <li class="description">Perfect for personal use.</li>
                            <li class="bullet-item">1GB Storage</li>
                            <li class="bullet-item">1 User</li>
                            <li class="bullet-item">24/7 Support</li>
                            <li class="cta-button"><a class="button success round" href="#">Sign Up</a></li>
                        </ul>
                    </div>
                    <div class="medium-4 columns">
                        <ul class="pricing-table pricing-team">
                            <li class="title">Team</li>
                            <li class="price">$50<small>/month</small></li>
                            <li class="description">For a small team.</li>
                            <li class="bullet-item">50GB Storage</li>
                            <li class="bullet-item">Up to 10 Users</li>
                            <li class="bullet-item">24/7 Support</li>
                            <li class="cta-button"><a class="button success round" href="#">Sign Up</a></li>
                        </ul>
                    </div>
                    <div class="medium-4 columns">
                        <ul class="pricing-table pricing-enterprise">
                            <li class="title">Enterprise</li>
                            <li class="price">$300<small>/month</small></li>
                            <li class="description">For large corporation</li>
                            <li class="bullet-item">Unlimited Storage</li>
                            <li class="bullet-item">Unlimited Users</li>
                            <li class="bullet-item">24/7 Priority Support</li>
                            <li class="cta-button"><a class="button success round" href="#">Sign Up</a></li>
                        </ul>
                    </div>
                </div>
            </div>
    </div>
  14. Finally, we add the website footer below the body content, as follows:
    </div> <!—the body content end --> 
    <footer class="startup-footer">
            <div class="row footer-nav">
                <ul class="secondary-nav">
                    <li><a href="#">About</a></li>
                    <li><a href="#">Contact</a></li>
                    <li><a href="#">Help</a></li>
                    <li><a href="#">Careers</a></li>
                    <li><a href="#">Terms</a></li>
                    <li><a href="#">Privacy</a></li>
                </ul>
                <ul class="social-nav">
                    <li><a class="foundicon-facebook" href="#">Facebook</a></li>
                    <li><a class="foundicon-twitter" href="#">Twitter</a></li>
                </ul>
            </div>
            <div class="row footer-copyright">
                <p>Copyright 2014 Super Awesome App. All rights reserved.</p>
            </div>
        </footer>
    </body> 
What just happened?

We just built the HTML markup for the website content and sections by following the Foundation guidelines. We also added extra classes along the way to customize the Foundation default
 

After constructing the website page markup in the previous chapter, we now start giving the website a look, feel, and colors. This time we will use Sassy CSS (SCSS), which also happens to be the underlying syntax of the Foundation default styles.

SCSS is a syntax variation of a CSS preprocessor named Sass. The Sass original syntax uses indentation formatting that makes the codes look neat. SCSS, on the other hand, uses curly braces and semicolons just like regular CSS. The similarity helps everyone to quickly grasp the syntax, in particular those who are new to Sass.

Since we are going to employ SCSS, we will start off this chapter by walking you through a couple of Sass features and its utilities. You will learn to define variables and functions, perform operations, and comply with other directives, which allows us to compose the website style rules more efficiently.

This might sound challenging. And if you like a challenge, we can just get started right away.

This chapter will revolve around the following topics:

Sass (http://sass-lang.com/) is a CSS preprocessor created by Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein, which is the same team that also created Haml (http://haml.info/). Foundation, as mentioned at the beginning of this chapter, uses Sass to generate its CSS, and so will we. So, before we get our hands dirty, first we will delve into several Sass features, such as nesting, variables, mixins, functions, and others, that will allow us to write style rules more efficiently.

A variable is one useful piece in programming language that allows us to define a value once within a specified name. Each language has a slightly different way to declare a variable. For example, JavaScript uses the keyword var, LESS uses @, and Sass in this case uses the $ sign.

One of the perfectly-suited implementations of a variable is to define the website colors, for example:

So, instead of declaring the color value every time we need it, we can simply declare the representative variables. In the following example, we declare $primary as the body text color and $secondary as the background color:

When compiled to regular CSS, these variables are replaced with the defined value, as follows:

Using a variable with a proper name (of course), you will find it easier to write the variable rather than remembering the Hex or the RGB number; well, it is practically easier to write $primary than #bdc3c7, isn't it?

The Sass variable isn't exclusively aimed to define colors. We can also use a variable to define a string or plain text, as follows:

We can use a variable to store a number or a length:

We can use a variable to inherit the value of another variable:

We can use a variable to define the output of a function:

Foundation centralized the declaration of its primary variables within a file named _settings.scss. We will look more into this matter later when we compose the website style rules.

There are certain circumstances when a variable is not applicable, such as when it is inserted within a string (plain text), as follows:

When compiled, the $var declaration within $newVar won't be replaced with the value of "Hello". This is because Sass interprets $var as a string or plain text. Thus, the output of the following example will simply be:

Another example where a variable won't work is when a declaration is begun with an @ rule or a directive, as follows:

This example simply returns an error to the Sass compiler because @media is supposed to be followed by either the print or screen keyword.

There are a few cases where we have to use interpolation to declare a variable. Variable interpolation happens to other programming languages, such as PHP, Ruby, and Swift. But I'm not going into the details of the technicalities of its workings, as I don't exactly know either. Simply put, interpolation allows us to embed a variable in a situation where it does not allow the variable to work—especially where it is a string that is actually expected.

Each programming language has its notation to enable interpolation. In this case, Sass uses #{}. Given one of the previous examples, we can write the variable as follows:

And the result will be as follows:

Now, we are going to look into Sass mixins. If you followed and accomplished the second project, you should know about LESS mixins. Mixins, both in Sass and LESS, have similar purposes; they allow developers to reuse code blocks and style rules within the entire style sheet and thus comply with the DRY principle (http://programmer.97things.oreilly.com/wiki/index.php/Don't_Repeat_Yourself). However, it is slightly different in terms of how we declare and reuse the mixins. This is how we declare a mixin in LESS:

.buttons { 
  color: @link-color;
  font-weight: normal;
  border-radius: 0; 
}

In Sass, we use the @mixins directive to create a mixin, for example:

$linkColor: $tertiary;
@mixin buttons { 
  color: $linkColor;
  font-weight: normal;
  border-radius: 0; 
}

Sass uses the @include directive to reuse the preceding code block within style rules. Given the preceding example, we can write:

.button {
   @include buttons;
}

The following is the output when the preceding example is compiled to CSS:

.button {
  color: #2ecc71;
  font-weight: normal;
  border-radius: 0;
}

That is a basic example of the application of Sass mixins.

Some CSS3 syntaxes are so complex that writing them can be really tedious work. And this is where mixins can be particularly useful. Fortunately, with Sass being so popular and supported by so many generous developers, we don't have to port all CSS3 syntax into Sass mixins on our own. Instead, we can simply employ Sass's mixin library that makes our work as a web developer more enjoyable.

The Sass library comes with a collection of useful mixins and functions (we will talk about functions shortly) that we can use right away out-of-the-box. There are dozens of popular libraries available, and one that we are going to use herein is called Bourbon (http://bourbon.io/).

Bourbon compiles a number of mixins in a library that simplifies the way we declare CSS3 syntax, including syntax that is still marked as experimental, such as image-rendering, filter, and the CSS3 calc function. Now, which do you think is easier and faster to write when it comes to specifying the Hi-DPI Media Query?

Is the following standard syntax?

@media only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (min--moz-device-pixel-ratio: 2),
only screen and (-o-min-device-pixel-ratio: 2 / 1),
only screen and (min-resolution: 192dpi),
only screen and (min-resolution: 2dppx) {
  width: 500px;
}

Or, will it be the following one with the Bourbon mixin?:

@include hidpi(2) {
  width: 500px;
}

Without spending years researching, we can commonly agree that using the mixin should be a lot easier to write, as well as easier to remember.

A function is one piece of a feature that makes creating style rules more dynamic. A function in Sass is declared using the @function directive, which is then followed by the function name, a parameter with preferably its default value. In its simplest form, a Sass function may look as follows:

This function, however, won't output anything yet. To generate a result of this function, we need to add a @return value. Given the preceding example, we want to output the default value parameter, which says "hello". To do so, we write the @return value, which is then followed by $parameter, as follows:

Use this function within a selector, as follows:

Compile it, and you get the following output:

Customize the output by specifying a new value out of the default one, as follows:

We will get a new output, as shown in the following code:

The Foundation framework comes with an array of its own functions. Foundation uses these functions to build its own default styles, and we can also use them to build our own. One such useful function therein is rem-calc(), which allows us to calculate the rem unit with less hassle.

The rem unit is a relative value that inherited concepts similar to em. Here is what Ian Yates expounded about the origin of em in his post (https://webdesign.tutsplus.com/articles/taking-the-erm-out-of-ems--webdesign-12321):

But the problem with the em unit, as Jonathan Snook described in his post (http://snook.ca/archives/html_and_css/font-size-with-rem), is its compounding nature. Since the size is relative to its closest parent, in my experience the size output can be unpredictably frustrating at best; the size will be varying depending on where it is specified. Examine the following example:

body {
    font-size:16px;
}
div {
    font-size: 1.2em; /* 19px */
} 
ul { 
    font-size: 1em; /* 19px */
}
ul li { 
    font-size: 1.2em; /* 23px */
}

This is where the rem unit comes in. The rem unit measures the calculation directly against the font size of <html>, the root element of an HTML document—thus, it is also dubbed as root em. Regardless of where the unit is specified, the result will be precise, consistent, and more importantly, easy to figure out (it's like the px unit, but it's relative).

The rem-calc function accepts both integer and length. Hence, the following code examples work:

In this case, they will turn out to be as follows:

In Chapter 7, A Responsive Website for Business with Foundation, we installed Foundation and Foundation Icons, along with their dependencies (jQuery, Fastclick, Modernizr, and so on) through Bower (http://bower.io/). We also prepared the website assets, namely, the images, image icons, and the website logo. In the last section of the chapter, we created index.html for the website home page, and we also constructed the markup using a couple of new HTML5 tags. So, the files and folders that are currently in the working directory are shown in the following screenshot:

Project recap

Perform the following steps right to the end to properly organize the style sheets and compile them into CSS.

  1. We need to install Bourbon. Launch a terminal or the command prompt, and type the following command:
    bower install bourbon --save
    

    This command installs the Bourbon package through the Bower registry and registers it within the bower.json file of the project.

  2. Create new style sheets named main.scss, responsive.scss, and styles.scss in the scss folder.
  3. The _main.scss style sheet is the one where we will put all our own style rules. We will use the _responsive.scss file to exclusively put in the media queries of the website. And the styles.scss file is where we will compile those style sheets together.
  4. Still within the scss folder, create two more style sheets. This time, name them _config.scss and foundation.scss.
  5. The _config.scss will contain a copy of all the variables used in Foundation, while foundation.scss will contain imported partials of Foundation style sheets. These copies will prevent us from directly modifying the original files, which will eventually be overridden when we update to the newest version.
  6. Next, copy the whole content of the Foundation _settings.scss file to the _config.scss file that we recently created. In our case, the _settings.scss file is located in the /components/foundation/scss/foundation/ directory.
  7. Also, copy the whole content of Foundation's own foundation.scss and paste it to our own foundation.scss that we also recently created.
  8. Then, we need to correct the path of the imported partials in our foundation.scss file. At this stage, all paths are pointing to the foundation folder, as follows:
    @import "foundation/components/grid";
    @import "foundation/components/accordion";
    @import "foundation/components/alert-boxes";
    ... /* other imports */

    This certainly is incorrect because we don't have a folder named foundation in the scss folder. Herein, we need to direct the path to the components folder instead, where the partials actually reside. So, change the path to be as follows:

    @import "../../components/foundation/scss/foundation/components/grid";
    @import "../../components/foundation/scss/foundation/components/accordion";
    @import "../../components/foundation/scss/foundation/components/alert-boxes";
    ... /* other imports */
  9. Another path that we have to correct is the path referring to the Foundation, _functions.scss, which contains the rem-calc() function. Open the _config.scss file, and change the line @import "foundation/functions"; to @import "../../components/foundation/scss/foundation/functions";.
  10. We are going to compile these style sheets into CSS using Koala. Launch Koala and add the working directory:
    Time for action – organizing and compiling style sheets
  11. Within the style list in Koala, you won't find the SCSS style sheets with the underscore prefix. Koala, by default, ignores this file since it eventually won't be compiled into CSS.
  12. However, you should find the two primary style sheets of the project listed therein, namely, styles.scss and foundation.scss. Be sure that this output is set to the css folder, as shown in the following screenshot:
    Time for action – organizing and compiling style sheets
  13. Then, make sure that the option of Auto Compile is checked so that they will be automatically compiled into CSS, as we've made changes. Also, check the Source Map option to make debugging the style sheet easier. Have a look at the following screenshot:
    Time for action – organizing and compiling style sheets
  14. Click the Compile button of styles.scss and foundation.scss to compile them into CSS.
  15. Open index.html and link both the compiled CSSs within the <head> tag, as follows:
    <link rel="stylesheet" href="assets/css/foundation.css">
    <link rel="stylesheet" href="assets/css/styles.css">
What just happened?

We just installed Bourbon and put together several new style sheets to style the website. Then, we compiled them into CSS, and then linked them to index.html. Hence, as you can see in the following screenshot, the website is now starting to take place—with the Foundation default styles:

What just happened?

Styling the website will involve multiple style sheets. Hence, follow the following steps carefully:

  1. Import the following style sheets in foundation.scss:
    @import "config";
    @import "../../components/foundation/scss/normalize";
    @import "../../components/foundation-icons/foundation_icons_social/sass/social_foundicons.scss";
    ... /* other partials */

    That way, the variables, as well as the changes within _config.scss, will affect other component style sheets through Foundation. The normalize variable will standardize basic element styles, social_foundicons.scss; as you can guess, this allows us to apply Foundation's social icons.

  2. Open styles.scss and import Bourbon, _config.scss, main.scss, and responsive.scss, as follows:
    @import "../../components/bourbon/dist/bourbon";
    @import "config";
    @import "main";
    @import "responsive"; 
  3. Then, I want to apply a custom font from Google Font simply because the custom fonts look better than the average font system, such as Arial or Times. Herein, I picked a font named Varela Round (https://www.google.com/fonts/specimen/Varela+Round).
  4. Open index.html, and add the font style sheet within the <head> tag, as follows:
    <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Varela+Round' type='text/css'>
  5. Now, we will change the font-family stack, which is currently specified as the Foundation default font, to use Varela Round.
  6. To do so, open _config.scss, uncomment the variable named $body-font-family, and insert "Varela Round", as follows:
    $body-font-family: "Varela Round", "Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif;
  7. We will style each of the website sections. To begin with, we will focus on the website header, and then, subsequently down to the footer. Let's start off by adding an image background. Open _main.scss and then add the following lines:
    .startup-header {
      background: url('../img/banner.jpg') no-repeat center center fixed;
      background-size: cover;
    } 

    The image, however, is currently hidden at the back of the background color that applies to the top bar and a section in which Foundation named it Panel (http://foundation.zurb.com/docs/components/panels.html), as shown in the following screenshot:

    Time for action – build on the website
  8. Remove these background colors so that we can see through the background image. To do so, open the _config.scss file and uncomment the following lines:
    $topbar-bg-color: #333;
    $topbar-bg: $topbar-bg-color;

    Change the value of the $topbar-bg-color variable from #333 to transparent

    $topbar-bg: transparent;
  9. Uncomment this following line, which specifies the panel's background color:
    $panel-bg: scale-color($white, $lightness: -5%);

    Then, change the value to transparent as well:

    $panel-bg: transparent;

    Now, we can see the background image, which is shown in the following screenshot:

    Time for action – build on the website
  10. From the preceding screenshot, it is evident that the top bar and the panel background color have been removed, but some of the menu items still have it.
  11. Let's remove these background colors. In _config.scss, uncomment the following line:
    $topbar-dropdown-bg: #333;

    And change the value to use the value of the $topbar-bg variable, as follows:

    $topbar-dropdown-bg: $topbar-bg;
  12. Save it and let a few seconds pass for the files to be compiled, and you should see now that the background color of those menu items are removed, as shown in the following screenshot:
    Time for action – build on the website
  13. Add padding-top to give more distance between the top bar and the upper boundary of the browser viewport:
    .startup-header {
    ...
      .startup-top-bar {
        padding-top: rem-calc(30);
      }
    }

    And now, as you can see, there is more breadth therein:

    Time for action – build on the website

    The left-half of the image is before we add the padding-top, and the right-half definitely is after we add the padding-top.

  14. Give more padding at the top and bottom of the panel section; hence, we can view more of the background image. Nest the style rules under the .startup-header, as follows:
    .startup-header {
      ...
      .startup-hero {
        padding-top: rem-calc(150px);
        padding-bottom: rem-calc(150px);
      }
    }
  15. Add the logo image, as follows:
    .startup-name {
      max-width: 60px;
      a {
        text-indent: 100%;
        white-space: nowrap;
        overflow: hidden;
        background: url('../img/logo.svg') no-repeat center left;
        background-size: auto 90%;
        opacity: 0.9;
      }
    }

    Now we have the logo added, as follows:

    Time for action – build on the website
  16. Hover over the menu links in the top bar, and you will find it with a dark background color, as follows:
    Time for action – build on the website

    This background color is not quite right when it comes to the website's aesthetic as a whole, so let's remove that. In _config.scss, uncomment the following lines:

    $topbar-link-bg-hover: #272727;

    Then, change the value to transparent by inheriting the value of the $topbar-bg variable, as follows:

    $topbar-link-bg-hover: $topbar-bg;
  17. Turn the menu links to uppercase so that it looks slightly bigger. Set the variable named $topbar-link-text-transform in _config.scss from none to uppercase:
    $topbar-link-text-transform: uppercase;
  18. The next thing we will do is change the styles of the two buttons: Login and Sign Up. We will make it just a little bit more fashionable, and the following are all the new styles for these buttons; nest these lines under the .startup-header:
    .startup-header {
    ...
    .startup-top-bar {
      padding-top: rem-calc(30);
        ul {
    $color: fade-out(#fff, 0.8);
    $color-hover: fade-out(#fff, 0.5);
        background-color: transparent;
        .button {
    @include transition (border 300ms ease-out, background-color 300ms ease-out);
        }
        .log-in {
      padding-right: 0;
          > .button {
            background-color: transparent;
            border: 2px solid $color;
            color: #fff;
            &:hover {
          background-color: transparent;
          border: 2px solid $color-hover;
          color: #fff;
            }
          }
        }
        .sign-up {
          > .button {
          background-color: $color;
          border: 2px solid transparent;
          color: #fff;
          &:hover {
            background-color: $color-hover;
            border: 2px solid transparent;
          }
        }
         }
       }
      } 
    }

    Now, the buttons should look as shown in the following screenshot. Hover over the button, and you will see nice little transition effects that we added through the transition() mixin of Bourbon:

    Time for action – build on the website

    However, it's worth noticing that I consider this merely as decoration. It's up to you to customize the button styles.

  19. With buttons on a transparent background, let's make three menu link items on the left-hand side, namely, PRICES, PRICING, and BLOG, slightly transparent as well. To do so, uncomment and change the variable named $topbar-link-color in _config.scss to fade-out(#fff, 0.3), as follows:
    $topbar-link-color: fade-out(#fff, 0.3);
  20. Then, let's give the links a transition effect. Add the following lines in _main.scss:
    .startup-header {
    ...
      .startup-top-bar {
        ...
        a {
         @include transition(color 300ms ease-out);
          }
       }
     }
  21. Next, we will add a dark transparent layer on the header. By adding this dark layer, the text in the header can be more distinct over the background image.

    Add the following lines in _main.scss:

    .startup-header {
    ...
      .startup-top-bar,
      .startup-hero {
        background-color: fade-out(#000, 0.5);
      }
    }
  22. Add the following lines as our last touch for the header section:
    .startup-header {
    ...
      .startup-hero {
        padding-top: rem-calc(150px);
        padding-bottom: rem-calc(150px);
        .hero-lead {
          color: darken(#fff, 30%);
        }
      }
    ...
    }

    Now, we have a nice header for the website, as you can see in the following screenshot:

    Time for action – build on the website
  23. With the website styled, we will move to the next section. Below the header, we have the feature section that contains a number of key features of our products and services. And these are all the styles for the feature section:
    ...
    .startup-features {
      padding: rem-calc(90 0);
      figure {
        margin: 0;
      }
      .columns {
        margin-bottom: rem-calc(15);
      }
    }

    In the preceding snippet, we remove the margin from the figure element that wraps the image icon. This will give the image icons figure more room to span, as you can see in the following screenshot:

    Time for action – build on the website

    Other than that, margin-bottom, as well as the padding we added in conjunction with it, simply gives this section more whitespace.

  24. Below the feature section, we have the section that shows happy customers speaking. We call it the testimonial section. Add the following style rules to build on it:
    .startup-testimonial {
      padding: rem-calc(90 0);
      text-align: center;
      background-color: darken(#fff, 2%);
      blockquote {
        font-size: rem-calc(24);
      }
      figure {
        margin-top: 0;
        margin-bottom: 0;
        .avatar {
          border-radius: 50%;
          display: inline-block;
          width: 64px;
        }
      }
      figcaption {
        margin-top: rem-calc(20);
        color: darken(#fff, 30%);;
      }
    }
  25. Also, remove the blockquote element's left-hand side border by changing the value of $blockquote-border in _config.scss, as follows:
    $blockquote-border: 0 solid #ddd;

    Note that the preceding styles are merely decoration. At this stage, this is how the testimonial section looks:

    Time for action – build on the website

    Don't freak out, it's not broken. The remaining styles will be added through the Orbit Slider plugin once it is enabled. We will take a look at the steps for this shortly.

  26. Next, we will style the price and plan tables. These are all the styles for the table price, and their main purpose is to give each table a distinct color.
    .startup-pricing {
      $basic-bg      : #85c1d0;
      $team-bg       : #9489a3;
      $enterprise-bg : #d04040;
    
      padding-top: rem-calc(120);
      padding-bottom: rem-calc(120);
      .pricing-table {
        background-color: darken(#fff, 2%);
      }
      .pricing-basic {
        .title {
          background-color: $basic-bg;
        }
        .price {
          background-color: lighten($basic-bg, 25%);
        }
      }
      .pricing-team {
        .title {
          background-color: $team-bg;
        }
        .price {
          background-color: lighten($team-bg, 25%);
        }
      }
      .pricing-enterprise {
      .title {
          background-color: $enterprise-bg;
        }
        .price {
          background-color: lighten($enterprise-bg, 25%);
        }
       }
    }
  27. The footer section is bare and straightforward. There's nothing prominent. There is just a bunch of style rules to make the footer look nicer, as follows:
    .startup-footer {
      $footer-bg: darken(#fff, 5%);
      text-align: center;
      padding: rem-calc(60 0 30);
      background-color: $footer-bg;
      border-top: 1px solid darken($footer-bg, 15%);
      .footer-nav {
        ul {
          margin-left: 0;
        }
        li {
          display: inline-block;
          margin: rem-calc(0 10);
        }
        a {
          color: darken($footer-bg, 30%);
          @include transition (color 300ms ease-out);
          &:hover {
            color: darken($footer-bg, 70%);
          }
        }
      }
      .social-nav {
        li a:before {
          margin-right: rem-calc(5);
          position: relative;
          top: 2px;
        }
        .foundicon-facebook:hover {
          color: #3b5998;
        }
        .foundicon-twitter:hover {
          color: #55acee;
        }
      }
      .footer-copyright {
        margin-top: rem-calc(30);
        color: darken($footer-bg, 15%);
      }
    }
What just happened?

In this section, we Have a go hero – colors and creativities

I realize that good, bad, nice, and not nice are highly subjective. It all depends on individual preference and their degree of taste. So, if the website decoration, such as colors, fonts, and sizes, that we specified in the preceding steps are not up your alley, you can freely change them and add your own creativity. Pop quiz – importing an external Sass style sheet

Q1. Hopefully, you followed the preceding steps fully through and paid attention to some of the minute details. We have imported a number of style sheets to compile them into a single style sheet. How do we make the Sass compiler ignore these imported style sheets so that the compiler won't compile them into a CSS file on its own?

Remove the extension file's extension in the import declaration.
Add an underscore as a prefix in the import declaration.
Add an underscore as a prefix in the file name.

Perform the following steps to compile the JavaScript files and optimize the website for a small viewport size:

  1. Create a new JavaScript file in the assets/js directory named foundation.js.
  2. In foundation.js, import the following JavaScript files:
    // @koala-prepend "../../components/foundation/js/vendor/jquery.js"
    // @koala-prepend "../../components/foundation/js/foundation/foundation.js"
    // @koala-prepend "../../components/foundation/js/foundation/foundation.topbar.js"
    // @koala-prepend "../../components/foundation/js/foundation/foundation.orbit.js"
  3. Via Koala, compile foundation.js.
  4. Then, open index.html and add the following lines right before </body> to enable the Orbit Slider functionalities:
    <script src="assets/js/foundation.min.js"></script>
    <script>
    $(document).foundation({
         orbit: {
           timer_speed: 3000,
           pause_on_hover: true,
           resume_on_mouseout: true,
           slide_number: false
         }
        });
    </script>
  5. Now, we will refine the website layout for smaller viewport viewing with media queries. To do so, we need to uncomment the variables that define the media query ranges used in Foundation, so that we can use them in our style sheets as well:
    $small-range: (0em, 40em);
    $medium-range: (40.063em, 64em);
    $large-range: (64.063em, 90em);
    $xlarge-range: (90.063em, 120em);
    $xxlarge-range: (120.063em, 99999999em);
    
    $screen: "only screen";
    
    $landscape: "#{$screen} and (orientation: landscape)";
    $portrait: "#{$screen} and (orientation: portrait)";
    
    $small-up: $screen;
    $small-only: "#{$screen} and (max-width: #{upper-bound($small-range)})";
    
    $medium-up: "#{$screen} and (min-width:#{lower-bound($medium-range)})";
    $medium-only: "#{$screen} and (min-width:#{lower-bound($medium-range)}) and (max-width:#{upper-bound($medium-range)})";
    
    $large-up: "#{$screen} and (min-width:#{lower-bound($large-range)})";
    $large-only: "#{$screen} and (min-width:#{lower-bound($large-range)}) and (max-width:#{upper-bound($large-range)})";
    
    $xlarge-up: "#{$screen} and (min-width:#{lower-bound($xlarge-range)})";
    $xlarge-only: "#{$screen} and (min-width:#{lower-bound($xlarge-range)}) and (max-width:#{upper-bound($xlarge-range)})";
    
    $xxlarge-up: "#{$screen} and (min-width:#{lower-bound($xxlarge-range)})";
    $xxlarge-only: "#{$screen} and (min-width:#{lower-bound($xxlarge-range)}) and (max-width:#{upper-bound($xxlarge-range)})";
  6. Now, we will define a couple of style rules through these media queries to adjust the website's styles, particularly the sizing, positioning, and whitespace.
  7. And these are all the style rules to add in _responsive.scss.
    @media #{$small-up} {
      .startup-name a {
        position: relative;
        left: rem-calc(15);
      }
    }
    @media #{$small-only} {
      .startup-header {
        .startup-name a {
          background-size: auto 80%;
        }
        .startup-top-bar {
          padding-top: rem-calc(15);
          .top-bar-section {
            text-align: center;
          }
          .sign-up {
            padding-top: 0;
          }
        }
        .startup-hero {
          text-align: center;
        }
      }
      .startup-footer {
        .secondary-nav {
          li, a {
            display: block;
          }
          a {
            padding: rem-calc(10);
          }
        }
      }
    }
    @media #{$medium-up} {
      .startup-top-bar {
        .log-in {
          padding-right: 3px; 
        }
        .sign-up {
          padding-left: 3px; 
        }
      }
    }
    @media #{$large-only} {
        .startup-name a {
        position: relative;
        left: rem-calc(0);
      }
    } 
What just happened?

We just compiled the Have a go hero – remove unnecessary Foundation components

We include all the Foundation components, even ones we are not using in the website. Hence, it is better to remove all the styles which do not give an advantage to the website. Open _foundation.scss, and comment the @import components that we do not need (at least at this moment) and recompile the style sheets.

 
Pop quiz – web development tools and command lines

Q1.

1

Q2.

2

Pop quiz – using polyfill

Q1.

2

Q1.

2

Q2.

2

Q3.

1

Pop quiz – HTML5 elements

Q1.

2

Q2.

2

Q3.

1

Pop quiz – website performance rules

Q1.

4

Pop quiz – test your understanding on Bower commands

Q1.

2

Q2.

1

Q3.

2

Pop quiz – Bootstrap button classes

Q1.

5

Q2.

1

Pop quiz – which of the following option is not LESS Import option? Pop quiz – using LESS function and extend syntax

Q1.

2

Q2.

1

Q3.

2

Pop quiz – multiple parameters in Sass function Pop quiz – Sass color manipulation Pop quiz – importing external Sass style sheet

Q1.

1

About the Authors
  • Ben Frain

    Ben Frain has been a web designer/developer since 1996. He is currently employed as a UI-UX Technical Lead at bet365. Before the web, he worked as an underrated (and modest) TV actor and technology journalist, having graduated from Salford University with a degree in Media and Performance. He has written four equally underrated (his opinion) screenplays and still harbors the (fading) belief he might sell one. Outside of work, he enjoys simple pleasures: playing indoor football while his body and wife still allow it and wrestling with his two sons.

    Browse publications by this author
  • Thoriq Firdaus

    Thoriq Firdaus is a web developer and lives in Indonesia. He has been dabbling in web design and development for more than 5 years, working with many clients of varying sizes. He appreciates the giving nature of the web design community at large. He also loves trying out new things in CSS3 and HTML5 and occasionally speaks at some local colleges and institutions on the subject. Outside of work, he loves spending time with his wife and daughter, watching movies, and enjoying meals at nearby cafes and restaurants.

    Browse publications by this author
  • Benjamin LaGrone

    Benjamin LaGrone is a web developer who lives and works in Texas. He got his start in programming at the age of 6 when he took his first computer class at the Houston Museum of Natural Science. His first program was "choose your own adventure book", written in BASIC; he has fond memories of the days when software needed you to write line numbers. Fast forward to about thirty years later: after deciding that computers are here to stay, Ben has made a career combining two of his favorite things, art and codingcreating art from code. One of his favorite projects was using the GMaps API to map pathologies to chromosomes for cancer research. Fascinated with mobile devices for a long time, Ben thinks that the responsive Web is one of the most exciting, yet long time coming, new aspects of web development. He now works in a SaaS development shop and is the mobile and responsive Web evangelist of the team. When he's not working on some Internet project, Ben spends his time building robots, tinkering with machines, drinking coffee, surfing, and teaching Kuk Sool martial arts.

    Browse publications by this author
Latest Reviews (9 reviews total)
The topic is too wide, however I would like to get some more details about each responsive framework. I haven't read the whole book so far, so it might have enough info in the next pages....
good book so far x x x x x this is silly requiring so many characters. Who thought this was a good idea?
read first chapter so far.
HTML5 and CSS3: Building Responsive Websites
Unlock this book and the full library FREE for 7 days
Start now