Responsive Web Design by Example : Beginner's Guide

By Thoriq Firdaus
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Responsive Web Design

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. You can now create your very own responsive website quickly and efficiently, allowing you to showcase your content in a format that will work on any device with an Internet browser.

By following our detailed step-by-step instructions in this structured reference guide, you will learn how you can build engaging responsive websites. With coverage of Bootstrap, Skeleton, and Zurb Foundation you'll learn about three of the most powerful responsive frameworks available today.

Leading you through by practical example, you'll find that this essential reference develops your understanding by actually helping you create beautiful websites step by step in front of your very eyes. After going over the basics, you'll be able to choose between creating your own responsive portfolio page with Skeleton, building a stunning product page with Bootstrap, or setting up your own professional business website with Zurb Foundation. Ultimately you'll learn how to decide which framework is right for you, and how you can deploy and customize it to your exact specifications!

Publication date:
March 2013
Publisher
Packt
Pages
338
ISBN
9781849695428

 

Chapter 1. Responsive Web Design

The number of users and features for mobile devices have been increasing exponentially in the last few years. Mobile browsers can now render web pages as good as desktop browsers can, so it is now a common sight to see people enjoying browsing through websites from their phones or tablets. The number of mobile users will grow even larger in the future; Cisco predicts that there will be about 788 million mobile-only users by 2015 [http://www.cisco.com/en/US/solutions/collateral/ns341/ns525/ns537/ns705/ns827/white_paper_c11-520862.pdf].

This event surely comes with a consequence on the other side. Designers are forced to think of new ways to deliver web pages for mobile users; we can definitely no longer rely on the static grid, since the sizes of mobile devices are too varied. In 2010, Ethan Marcotte [http://ethanmarcotte.com/] coined a new answer to this situation called responsive web design [RWD] that now has become a popular practice in web design to deliver web pages in varying viewport sizes [http://www.alistapart.com/articles/responsive-web-design/].

Tip

John Allsopp (http://johnfallsopp.com/) had actually foretold the adaptability of web pages twelve years earlier in his post A Dao of Web Design (http://www.alistapart.com/articles/dao/).

In this first chapter we will:

  • Take a glance at the basics of responsive web design and its current limitations

  • Take a look at the responsive frameworks that we are going to use to build responsive websites

  • Look into CSS preprocessors and their syntax to compose styles

  • Prepare the tools to build responsive websites

Let's get started.

 

Basic responsive web design


RWD basically allows a website to respond or adapt to a different viewport size, smaller or larger, without your having to set a specific domain/subdomain for people using mobile devices. The look and feel of the website can be maintained as to have similar experiences across different device sizes. This is possible with the use of viewport meta tag and CSS3 media queries.

Viewport meta tag and CSS3 media queries

A responsive website is primarily built with two components. The first component is the viewport meta tag (http://developer.apple.com/library/ios/#documentation/AppleApplications/Reference/SafariWebContent/UsingtheViewport/UsingtheViewport.html). This tag is placed inside the <head> tag and is used to control the scale of the web page.

For example, adding the following viewport meta tag with initial-scale set to 1 will allow the web page to be scaled by 100 percent of the viewport size upon opening it for the first time.

<meta name="viewport" content="width=device-width, initial-scale=1">

Note

Ian Yates (http://www.snaptin.com/) has exclusively covered the use of the viewport meta tag in his post at Webdesigntuts+ (http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/quick-tip-dont-forget-the-viewport-meta-tag/).

The second component is the CSS3 media queries (http://www.w3.org/TR/css3-mediaqueries/), which specify the styles for specific viewport sizes. For instance, the following code snippet shows how we can hide images when the viewport size is between 321 px and 480 px:

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

@media screen and (min-width: 321px) and (max-width: 480px) {
  img { display: none; }
}

The SmashingMagazine website (http://www.smashingmagazine.com/) is a good example to illustrate how responsive web design is executed; the following screenshot shows how it is displayed in two different viewports. Note how the search button text changes from Search to Go! in the smaller viewport size.

The website http://www.barackobama.com/ is also a good example of a responsive website:

Note

For more inspiration on responsive websites, you can visit http://mediaqueri.es/.

 

Limitations of responsive web design


At this point, RWD is not quite perfect; there are several issues to be resolved, including making the image responsive. The current practice for making the image responsive is to scale it to fit the viewport with max-width: 100%, or possibly to hide it with display: none when the image is not needed.

The problem with this practice is that it only alters the image presentation on the surface, while the actual image on the HTML document remains unaffected. This means that the users will still be downloading the same image resolution with a larger size regardless of their device and viewport size, which will result in wasted bandwidth consumption and could also hurt website performance particularly for mobile users.

From the preceding screenshot, you can see that the image is resized responsively to the viewport size, however the image resolution and size has not changed.

Responsive image with picture element

Recently at World Wide Web Consortium (W3C ), a group called Responsive Image Community Group (http://www.w3.org/community/respimg/) proposed a new element called <picture> to address the situation. This <picture> element enables the delivery of a proper image size and resolution based on a particular situation. It is worth noting that this new element, at the time of the writing, is still in the draft stage, which means that it is yet to be implemented by the browser vendors. This specification may be changed or even removed in the future.

Now let's take a look at the following code example:

<picture alt="responsive images">
  <source src=big.jpg media="min-width:768px">
  <source src=medium.jpg media="min-width:320px">
  <source src=small.jpg>
  <img src=medium.jpg alt="responsive images">
</picture>

The preceding code snippet will deliver the big.jpg image file with a high resolution and probably a wider width only when the viewport is at a minimum of 768px, while the medium.jpg image file with a lower resolution and file size will be delivered when the viewport is at a minimum of 320px.

Then, when these conditions are not met, the smaller image small.jpg will be delivered. Lastly, at the bottom of the list, we also have one more image with the <img> element; this is additionally used to provide a backup image for the browsers that do not support the <picture> element.

Let's see how we can use this element in a situation where scaling down the image is not the suitable approach.

Let's say we have an extremely wide image like a panorama and want to use it as the header on our website. When we'll view this image on the desktop's screen, we most likely won't find any issue, and the image will be clearly viewable.

However, when we view this image in a smaller viewport, the image is now too narrow and the people in the image are barely viewable. If there is text in the image, reading it will be hard on the eyes.

In this case, it will be more sensible to display different image proportions rather than scaling down the image, and using the <picture> element, this scenario would become possible. The following screenshot shows how we replace the image with the cropped version for a smaller viewport. Do you notice the difference? The people in this image look closer.

Note

If you can't wait to implement this ideal responsive image as demonstrated with the <picture> element, you can use a server-side solution with Adaptive Image (http://adaptive-images.com/) created by Matt Wilcox (http://mattwilcox.net/); technically, it will detect the user's screen size and deliver the appropriate image based on the screen size.

Or you can also use a polyfill (http://remysharp.com/2010/10/08/what-is-a-polyfill/) to mimic the <picture> element functionality (https://github.com/scottjehl/picturefill).

Furthermore, at .NET magazine (http://www.netmagazine.com/), James Young (http://offroadcode.com/) has done a survey for his fellow designers to understand the common problems with responsive web design and how to avoid them. You can head over to the post at http://www.netmagazine.com/features/top-responsive-web-design-problems-and-how-avoid-them and join the discussion.

 

Learn more about HTML5 and CSS3


Having a fairly good understanding of basic HTML5 or CSS3 would be really helpful to follow the projects in this book. You shouldn't be afraid though, as we will explain what the code in this book does, in order for you to understand what is happening in each step of building responsive websites.

Additionally, Packt Publishing has published a book covering these subjects in depth; it is called Responsive Web Design with HTML5 and CSS3 (http://www.packtpub.com/responsive-web-design-with-html-5-and-css3/book) written by Ben Frain (http://www.benfrain.com/). It is a good book for you to start digging into HTML5, CSS3, and responsive web design.

Note

Just in case this is your first time of dealing with HTML5 and CSS3, there are many good resources to help you understand these subjects in more detail.

Or else, if you are still puzzled with what RWD is all about, at this point we suggest you watch the screencast Braindump on Responsive Web Design (http://css-tricks.com/video-screencasts/102-braindump-on-responsive-web-design/) by Chris Coyier that is available at CSS Tricks (http://css-tricks.com/).

 

Introduction to RWD frameworks


Certainly, whether you are a beginner designer or an expert, creating a responsive website from the ground up can be convoluted. This is probably because of some indispensable technical issues in RWD, such as determining the proper number of columns in the grid and calculating the percentage of the width for each column, determining the correct breakpoint, and other technicalities that usually appear in the development stage. So in this book, rather than creating responsive web design from scratch, we will be using frameworks to help us out and make things a little easier in the process.

Note

Many threads regarding the issues of creating responsive websites are open on StackOverflow:

Why use frameworks?

Following are a few reasons why using a framework is considered a good option:

  • Time saver: If done right, using a framework could obviously save a lot of time. A framework generally comes with predefined styles and rules, such as the width of the gird, the button styles, font sizes, form styles, CSS reset, and other aspects to build a website. So, we don't have to repeat the same process from the beginning but simply follow the instructions to apply the styles and structure the markup. Bootstrap, for example, has been equipped with grid styles (http://twitter.github.com/bootstrap/scaffolding.html), basic styles (http://twitter.github.com/bootstrap/base-css.html), and user interface styles (http://twitter.github.com/bootstrap/components.html).

  • Community and extension: A popular framework will most likely have an active community that extends the framework functionality. jQuery UI Bootstrap is perhaps a good example in this case; it is a theme for jQuery UI that matches the look and feel of the Bootstrap original theme. Also, Skeleton, one of the frameworks we are going to use in this book, has been extended to the WordPress theme (http://themes.simplethemes.com/skeleton/) and to Drupal (http://demo.drupalizing.com/?theme=skeleton).

  • Cross browser compatibility: This task of assuring how the web page is displayed on different browsers is a really painful one. With a framework, we can minimize this hurdle, since the developers, most likely, have done this job before the framework is released publicly. Foundation is a good example in this case. It has been tested in the iOS, Android, and Windows Phone 7 browsers (http://foundation.zurb.com/docs/support.html).

  • Documentation: A good framework also comes with documentation. The documentation will be very helpful when we are working with a team, to get members on the same page and make them follow the standard code-writing convention. Bootstrap (http://twitter.github.com/bootstrap/getting-started.html) and Foundation (http://foundation.zurb.com/docs/index.php), for example, have provided detailed documentation on how to use the framework.

There are actually many responsive frameworks to choose from, but as we mentioned, the ones that we are going to use in this book are Skeleton, Bootstrap, and Foundation. Let's take a look.

Skeleton

Skeleton (http://www.getskeleton.com/) is a minimal responsive framework; if you have been working with the 960.gs framework (http://960.gs/), Skeleton should immediately look familiar. Skeleton is 960 pixels wide with 16 columns in its basic grid; the only difference is that the grid is now responsive by integrating the CSS3 media queries.

Note

In case this is the first time you have heard about 960.gs or Grid System, you can follow the screencast tutorial by Jeffrey Way available at http://learncss.tutsplus.com/lesson/css-frameworks/. In this screencast, he shows how Grid System works and also guides you to create a website with 960.gs. It is a good place to start with Grid System.

Bootstrap

Bootstrap (http://twitter.github.com/bootstrap/) was originally built by Mark Otto (http://markdotto.com) and only intended for internal use in Twitter. Short story: Bootstrap was then launched as a free software for public. In it's early development, the responsive feature was not yet included; it was then added in Version 2 in response to the increasing demand for RWD.

Bootstrap has a lot more added features as compared to Skeleton. It is packed with styled user interface components of commonly-used interfaces on a website, such as buttons, navigation, pagination, and forms. Beyond that, Bootstrap is also powered with some custom jQuery plugins, such as a tab, carousel, popover, and modal box.

To get started with Bootstrap, you can follow the tutorial series (http://www.youtube.com/playlist?list=PLA615C8C2E86B555E) by David Cochran (https://twitter.com/davidcochran). He has thoroughly explained from the basics to utilizing the plugins in this series.

Note

Bootstrap has been associated with Twitter so far, but since the author has departed from Twitter and Bootstrap itself has grown beyond expectation, Bootstrap is likely to get separated from the Twitter brand as well (http://blog.getbootstrap.com/2012/09/29/onward/).

Foundation

Foundation (http://foundation.zurb.com) was built by a team at ZURB (http://www.zurb.com/about/), a product design agency based in California. Similar to Bootstrap, Foundation is beyond just a responsive CSS framework; it is equipped with predefined styles for a common web user interface, such as buttons (http://foundation.zurb.com/docs/components/buttons.html), navigation (http://foundation.zurb.com/docs/components/top-bar.html), and forms. In addition to this, it has also been powered up with some jQuery plugins. A few high-profile brands, such as Pixar (http://projection.pixar.com/) and National Geographic Channel (http://globalcloset.education.nationalgeographic.com/), have built their website on top of this framework.

Who is using these frameworks?

Now, apart from the two high-profile names we have mentioned in the preceding section, it will be nice to see what other brands and websites have been doing with these frameworks to get inspired. Let's take a look.

Hivemind

Hivemind is a design firm based in Wisconsin. Their website (www.ourhivemind.com) has been built using Skeleton. As befits the Skeleton framework, their website is very neat, simple, and well structured. The following screenshot shows how it responds in different viewport sizes:

Living.is

Living.is (http://living.is) is a social sharing website for living room stuff, ideas, and inspiration, such as sofas, chairs, and shelves. Their website has been built using Bootstrap. If you have been examining the Bootstrap UI components yourself, you will immediately recognize this from the button styles. The following screenshot shows how the Living.is page is displayed in the large viewport size:

When viewed in a smaller viewport, the menu navigation is concatenated, turning into a navigation button with three stripes, as shown in the following screenshot. This approach now seems to be a popular practice, and this type of button is generally agreed to be a navigation button; the new Google Chrome website has also applied this button approach in their new release.

When we click or tap on this button, it will expand the navigation downward, as shown in the following screenshot:

Note

To get more inspiration from websites that are built with Bootstrap, you can visit http://builtwithbootstrap.com/. However, the websites listed are not all responsive.

Swizzle

Swizzle (www.getswizzle.com) is an online service and design studio based in Canada. Their website is built on Foundation. The following screenshot shows how it is displayed in the large viewport size:

Swizzle used a different way to deliver their navigation in a smaller viewport. Rather than expanding the menu as Bootstrap does, Swizzle replaces the menu navigation with a MENU link that refers to the navigation at the footer.

The cons

Using a framework also comes with its own problems. The most common problems found when adopting a framework are as follows:

  • Excessive codes: Since a framework is likely to be used widely, it needs to cover every design scenario, and so it also comes with extra styles that you might not need for your website. Surely, you can sort out the styles and remove them, but this process, depending on the framework, could take a lot of time and could also be a painful task.

  • Learning curve: The first time, it is likely that you will need to spend some time to learn how the framework works, including examining the CSS classes, the ID, and the names, and structuring HTML properly. But, this probably will only happen in your first try and won't be an issue once you are familiar with the framework.

  • Less flexibility: A framework comes with almost everything set up, including the grid width, button styles, and border radius, and follows the standard of its developers. If things don't work the way we want them to, changing it could take a lot of time, and if it is not done properly, it could ruin all other code structure.

Note

Other designers may also have particular issues regarding using a framework; you can further follow the discussion on this matter at http://stackoverflow.com/questions/203069/what-is-the-best-css-framework-and-are-they-worth-the-effort. The CSS Trick forum has also opened a similar thread on this topic at http://css-tricks.com/forums/discussion/11904/css-frameworks-the-pros-and-cons/p1.

 

Tools required to build responsive websites


There are several tools that we will need to build our website from the projects in this book. To build a responsive website, we will need web browsers, code editors, and responsive bookmarklets for responsive design testing.

Web browsers

We will need a browser to develop and view the result of our responsive websites. I personally suggest using Firefox (http://www.mozilla.org/firefox) or Chrome (www.google.com/chrome) as the main browser for development. You can also install Opera (http://www.opera.com/), Safari (http://www.apple.com/safari/), and Internet Explorer (http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-9/worldwide-languages) to make sure that the website is displayed properly in those browsers.

Code editors

A code editor is an indispensable equipment for developing a website. Technically, you can use any code editor as long as it can highlight the code properly.

My personal preference and the one that I have used in this book is Sublime Text 2. This editor is available for Windows, OS X, and Linux. It can be downloaded for free from http://www.sublimetext.com/2 for the purpose of evaluating with an unlimited period of time. However, it sometimes bugs you to purchase the license.

If you are annoyed with this behavior, consider purchasing the license or using other options for code editors.

Responsive bookmarklets

It is better to test responsive websites on real mobile devices, such as iPhones and iPads, Android or Windows Phones, and Nokia devices. But if the budget doesn't allow, you can use a tool called a responsive bookmarklet.

It is a sort of emulator tool to test responsive design by resizing the dimension of the viewable area in the browsers. There are a lot of responsive bookmarklets available today. Here are some of them:

If you are using Firefox 15 or higher (http://www.mozilla.org/en-US/firefox/new/), you can use its built-in feature called Responsive Design View. This can be accessed by navigating to Tools | Web Developer | Responsive Design View.

You can also have similar functionality in Chrome with an extension called Window Resizer (https://chrome.google.com/webstore/detail/kkelicaakdanhinjdeammmilcgefonfh). Safari users can use Resize Safari (http://resizesafari.com/).

 

A brief introduction to CSS preprocessors


There is one more thing to be discussed before we begin work on the projects in this book, namely CSS preprocessors. What are they? Simply put, a CSS preprocessor extends CSS capabilities. By using CSS preprocessor, we can compose CSS in more dynamic ways. CSS preprocessors allow us to use variables and functions, as in programming languages such as JavaScript and PHP, to compose the styles.

There are several CSS preprocessors available today, such as LESS (http://lesscss.org/), Sass (http://sass-lang.com/), and Stylus (http://learnboost.github.com/stylus/). However, in this book we will limit our discussion to LESS and Sass. As these are some CSS preprocessors that have been adopted in the responsive frameworks, we are going to use them in this book. Bootstrap utilizes LESS as its style foundation, while Sass is adopted in Foundation.

CSS preprocessor compiler tool

CSS preprocessors, such as LESS and Sass, are written in a language that browsers do not recognize. So we have to compile it into standard CSS form, which browsers can read, and deliver the result with a compiler. There are several CSS preprocessor compilers available today; following is the list:

Tool

Supported languages

OS

Price

Less.js (http://lesscss.org) and Node.js (http://nodejs.org/)

LESS

Windows, OS X, and Linux

Free

WinLESS (http://winless.org/)

LESS

Windows

Free

LESS.app (http://incident57.com/less/)

LESS

OS X

Free

Simpless (http://wearekiss.com/simpless)

LESS

Windows and OS X

Free

ScoutApp (http://mhs.github.com/scout-app/)

Sass

Windows and OS X

Free

ChrunchApp (http://crunchapp.net)

LESS

Windows, OS X, and Linux

Free

Terminal or Command Prompt

LESS and Sass

Windows, OS X, and Linux

Free

CompassApp (http://compass.handlino.com )

Sass

Windows, OS X, and Lunix

$ 10

Codekit (http://incident57.com/codekit/)

LESS, Sass, and Stylus

OS X

$ 25

The tools listed in the preceding table, particularly with GUI (graphical user interface ), are sufficiently easy to use. However, we will discuss this matter further when we are about to work on the projects. For now, let's see how we write styles in the LESS and Sass languages.

LESS

LESS is a JavaScript-based CSS preprocessor created by Alexis Sellier (http://alexissellier.com/). As mentioned, LESS is used by Bootstrap, one of the frameworks we will explore in this book. LESS allows us to compose styles with some programming features. The following are the ones that we may use frequently in the projects in this book:

  • Nesting rules

  • Variables

  • Mixins

  • Parametric mixins

  • Operation

Nesting rules

Traditionally in CSS, when we need to apply styles for the elements, let's say, under the nav element with class set to nav-primary, we may write the styles in the following way:

.nav-primary {
  background-color: #000;
  width: 100%;
}
.nav-primary ul {
  padding: 0;
  margin: 0;
}
.nav-primary li {
  display: inline;
}
.nav-primary li a {
  text-decoration: none;
  color: #fff;
}
.nav-primary li a:hover {
  color: #ccc;
}

As you can see, we repeat the parent class selector, .nav-primary, each time we apply styles to the elements under it. With LESS, we can eliminate this repetition and slightly simplify this code by nesting the CSS rules, as shown in the following example:

.nav-primary {
  background-color: #000;
  width: 100%;
  ul {
    padding: 0;
    margin: 0;
  }
  li {
    display: inline;
    a {
      text-decoration: none;
      color: #fff;
      &:hover {
        color: #ccc;
      }
    }
  }
}

There is nothing fancy in this code; we have just written it in a different way by nesting the style rules.

Variables

Variables in LESS, as in all programming languages, are useful to store a constant or fixed value; this value can later be assigned to the entire stylesheet. In LESS, a variable is defined with the @ sign and followed by the variable name. The variable name can be a combination of numbers and letters. In the following example, we will create some LESS variables to store colors and assign the variables to the style rules to pass the value.

@primaryColor: #234fb4;
@secondaryColor: #ffb400;
a {
  color: @primaryColor;
}
button {
  background-color: @secondaryColor;
}

In regular CSS, the preceding code will be compiled into the following code snippet:

a {
  color: #234fb4;
}
button {
  background-color: #ffb400;
}

Using variables, however, is not limited to storing colors, as we demonstrated in the preceding example. We can use variables for any other types of values, such as the radius size, for example:

@smallRadius: 3px; 

One of the advantages of using variables is that in case we need to make changes, we don't have to search through the entire stylesheet; we can simply change the variable. This certainly is a time saver.

Mixins

Mixins are like variables; however, rather than storing a single value, we are able to store a set of CSS properties. These properties can later be inherited by other CSS rulesets. Let's say we have the following CSS rules in the stylesheet:

.links {
  -webkit-border-radius: 3px;
  -mox-border-radius: 3px;
  border-radius: 3px;
  text-decoration: none;
  font-weight: bold;
}
.box {
  -webkit-border-radius: 3px;
  -mox-border-radius: 3px;
  border-radius: 3px;
  position: absolute;
  top: 0;
  left: 0;
}
.button {
  -webkit-border-radius: 3px;
  -mox-border-radius: 3px;
  border-radius: 3px;

}

In the preceding example, we declared border-radius in three different CSS rules. Each time we declare it in other CSS rules, we need to include the prefixes to cover earlier browsers. In LESS, we are able to concatenate this border radius and have it inherited by other CSS rules in the stylesheet using mixins. A mixin in LESS is simply defined with a class selector; in this example, we will create a mixin called .border-radius:

.border-radius {
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
}

Then, we can insert .border-radius to the other CSS rules to pass the same properties, as follows:

.links {
  .border-radius;
  text-decoration: none;
  font-weight: bold;
}
.box {
  .border-radius;
  position: absolute;
  top: 0;
  left: 0;
}
.button {
  .border-radius;
}

Parametric mixins

Furthermore, we can also extend mixins into a function, or in this case it is officially called parametric mixins. This method allows us to add an argument or variables and make the mixins configurable. Let's see the example discussed here.

We are still using our previous example. But this time, we will not assign a fixed value; instead we will replace it with a variable, as follows:

.border-radius(@radius) {
  -webkit-border-radius: @radius;
  -moz-border-radius: @radius;
  border-radius: @radius;
}

Now, we can insert this mixin into other CSS rulesets and assign a different value for each.

a {
  .border-radius(3px);
  text-decoration: none;
  font-weight: bold;
}
div {
  .border-radius(10px);
  position: absolute;
  top: 0;
  left: 0;
}
button {
  .border-radius(12px);
}

When we compile it into a regular CSS, the preceding LESS code will be converted into the following:

a {
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  text-decoration: none;
  font-weight: bold;
}
div {
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;
  position: absolute;
  top: 0;
  left: 0;
}
button {
  -webkit-border-radius: 12px;
  -moz-border-radius: 12px;
  border-radius: 12px;
}

As you can see from the examples, this practice could be very helpful when we are working with the CSS3 properties, eliminating the requirement to write the vendor prefixes repeatedly.

Note

There is a LESS extension called LESS Elements (http://lesselements.com/) that contains a number of very useful CSS3 mixins. If you plan to work with LESS, you can simply use this extension to cut your workload. Furthermore, SitePoint has also covered the use of LESS mixins in depth in a post available at http://www.sitepoint.com/a-comprehensive-introduction-to-less-mixins/.

Operations

We can also perform simple Math operations with LESS, such as addition, subtraction, division, and multiplication. Operations could be pretty useful in certain circumstances. In this example, we are going to calculate the proper width of the box by subtracting the padding from it so that it can fit in the parent container.

First, we will define the variable for the padding with the @padding variable:

@padding: 10px;

Then, we specify the box width and subtract the @padding variable from it:

.box {
  padding: @padding;
  width: 500px – (@padding * 2);
}

Remember that padding takes any two sides of the box, either the right and left or top and bottom, so as you can see that is why we multiply the @padding variable in the width property by 2. Finally when we compile this LESS operation into regular CSS, the example code will look like the following:

.box {
  padding: 10px;
  width: 480px;
}

In other cases, we can do the same to the height property, as follows:

.box {
  padding: @padding;
  width: 500px – (@padding * 2);
  height: 500px – (@padding * 2);
}

Sass (Syntactically Awesome Stylesheets)

Sass is a Ruby-based CSS preprocessor created by Hampton Catlin (http://www.hamptoncatlin.com/), Nathan Weizenbaum (http://nex-3.com/), and Chris Eppstein (http://chriseppstein.github.com/). Like LESS, Sass has the ability to add variables, mixins, and nesting rules, albeit with a few differences. Let's take a look at each of these.

Variables

In Sass, a variable is defined with the $ sign. Similar to our example with LESS, here we define the primary color in the Sass variable with $primaryColor and assign it to the style rules, as follows:

$primaryColor: #234fb4;
a {
  color: $primary;
}
button {
  background-color: $primaryColor;
}

Similar to LESS, when we compile this code into a regular CSS, it gets converted into the following:

a {
  color: #234fb4;
}
button {
  background-color: #234fb4;
}

Mixins

In Sass, a mixin is defined a bit differently than a mixin in LESS. The mixin in Sass is defined with the @mixin directive. Similar to our previous example in the LESS section, here we define a mixin for the border radius and then assign it to other rulesets with the @include directive, as follows:

@mixin border-radius {
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
}
a {
  @include border-radius;
  text-decoration: none;
  font-weight: bold;
}
div {
  @include border-radius;
  position: absolute;
  top: 0;
  left: 0;
}
button {
  @include border-radius;
}

Furthermore, we can also add an argument to a Sass mixin like we did in LESS, as follows:

@mixin border-radius($radius) {
  -webkit-border-radius: $radius;
  -moz-border-radius: $radius;
  border-radius: $radius;
}

Nested rules

Sass also allows us to nest rules, but it takes this method a step further. In Sass, we are able to nest individual property. Let me show you how to do it. First of all, in regular CSS, we sometimes define styles with their individual properties, as follows:

div {
  border-color: #ccc;
  border-style: solid;
  border-width: 5px;
}

In Sass, we can nest this rule in the following way:

div {
  border: {
    color: #ccc;
    style: solid;
    width: 5px;
  }
}

Selector inheritance

Selector inheritance sounds like a mixin, but it actually acts in a different way. While a mixin will inherit the styles to the other assigned selectors, selector inheritance will eventually group the selectors that share certain styles.

In the following example, we have the .button class, which defines the general styles of a button:

.button {
  padding: 5px 15px;
  border-radius: 3px;
  color: #fff;
  border: 1px solid #000;
}

We also have two types of buttons, namely Submit and Reset, and each will be defined with the .submit and .reset classes respectively. These buttons will have the general styles, except the background color, to convey their different purposes. In that case, we can utilize selector inheritance by assigning the .button class to other rulesets with the @extend directive, as shown in the following code snippet:

.submit {
  @extend .button;
  background-color: green;
}
.reset {
  @extend .button;
  background-color: red;
}

Unlike the mixin methods that simply duplicate the CSS properties to the assigned rulesets, selector inheritance, as mentioned, will group the selectors that share the same styles from the .button class. The preceding code will be converted into the following when compiled with regular CSS:

.button, .submit, .reset {
  padding: 5px 15px;
  border-radius: 3px;
  color: #fff;
  border: 1px solid #000;
}
.submit {
  background-color: green;
}
.reset {
  background-color: red;
}
 

Learning more on CSS preprocessors


Unfortunately, we are not going to dive further into the CSS preprocessor as it is actually beyond the scope of this book, and there are many other CSS preprocessor features that are yet to be covered. So if you are interested in the subject, I recommend you refer to the following sections.

Learning LESS

To learn more about LESS, refer to the documentations mentioned as follows:

Learning Sass

To learn more about Saas, refer to the documentations mentioned as follows:

Note

For further reference, Jonathan Verrecchia (http://verekia.com) has shared a good presentation slide about CSS preprocessors (http://www.slideshare.net/verekia/deep-dive-into-css-preprocessors). A few points that he has discussed in this presentation include CSS's limitations, a comparison between LESS, Sass, and Stylus, and also which CSS preprocessors you should use.

 

What are we going to create in this book?


Now that we have discussed the theoretical parts to equip us for our journey in this book, at this point you may be wondering exactly what are we going to create.

In this book, we are going to create three responsive websites with the frameworks that we have discussed earlier in this chapter, each with its own challenges. We most likely will also utilize the CSS preprocessor that comes with the frameworks, specifically with Bootstrap and Foundation.

Our first project in this book will be to create a responsive portfolio website with Skeleton. In the second project, we are going to create a responsive website for a product launch with Bootstrap. Lastly, we are going to build a responsive website with Foundation, for business purposes.

 

Summary


We discussed a lot of things in this first chapter. To sum up, we discussed the following:

  • The basic elements for creating a responsive website, viewport meta tag, and CSS3 media queries, as well as seeing a few well-executed responsive websites

  • The limitations of serving responsive images and also the current and future solution for this issue

  • The frameworks that we are going to use to build websites in this book, namely Skeleton, Bootstrap, and Foundation

  • CSS preprocessors to compose the styles for the websites LESS and Sass, as well as learning a few of their languages

In the next chapter, we will start our first project. We are going to create a responsive portfolio website using Skeleton.

About the 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
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial