Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

February 17 2014

14:00

January 31 2014

14:00

Learning SASS: A Beginner’s Guide to SASS

Writing a lot of CSS can be overwhelming; that is why learning SASS and LESS can make  any web developer and designer’s life much easier. For a beginner, you might find it fine but as time goes by and your CSS skills are improving. You begin to wonder if there is a way so that you don’t need to repeat a lot of CSS codes in your style sheet. The good news is, there is one! Thanks to the CSS pre – processor, it’s now possible to write concise CSS codes without repeating each of them again and again. It is even formatted nicely. You can perform computations and do dynamic styling using these pre-processing methods. There are two pre-processing methods that I will tackle: SASS and LESS. For this tutorial I will talk about SASS first and then on a separate tutorial, I’ll talk about LESS.

CSS Drawbacks

Using CSS only might work for you but when making big websites with multiple pages, there might be some features you wish CSS has. Take a look at the following disadvantages of using CSS alone.

  • No way to re-use common style rules.
  • No way to specify variables that can be defined and re-used all through the style sheet.
  • You can’t execute computations where you can add numerical values to elements.

Advantages of Using Pre-Processing Methods

While using CSS alone might give you nuisance, using pre-processing methods can save you a lot of time and effort. Check out the list of advantages of using pre-processing methods below.

  • Allows you to use variables that can be re-used all throughout the style sheet.
  • Higher level style syntax that provides advanced CSS features.
  • Compiled CSS files are uploaded to the production web server.

What Is SASS?

SASS stands for Syntactically Awesome Style Sheets and was  designed and created by Hampton Catlin. SASS manipulates CSS using variables, mixins, inheritance and nesting rules. Given the extensions .sass and .scss respectively, it’s translated to well-formatted CSS using a command line tool or web-framework plugin.

SASS makes it easier to write less CSS codes and manipulate them dynamically. It’s a great way to write more functional CSS codes and can speed up the workflow of every web developer and designer.

.sass VS. .scss Format

Before we begin on how to use SASS, let’s compare .sass and .scss extensions of SASS. First I will provide a simple CSS code and then I will show you how to simplify them on both extensions of SASS.

CSS Code

For our CSS, I used a header tag and put a zero value for margin and padding then white color for its text color.


header {
     margin: 0;
     padding: 0;
     color: #fff;
}

.scss Extension Format (New Way of Writing SASS)

To format this into .scss extension format, we will use a variable $color and give it a hexadecimal color value of #fff for white color. And then under the CSS style, instead of putting a hexadecimal color value of #fff, use the variable $color that was set in the beginning of the code.

$color:  #fff;
header {
    margin: 0;
    padding:0;
    color: $color;
}

.sass Extension Format (Old Way of Writing SASS)

For our .sass extension, we will have the same variable and value just like the .scss extension format, but, this time, without semi-colons and brackets. Notice that indentions are more reliant. This is the old format in writing SASS.

$color: #fff
header
   margin: 0
   padding: 0
   color: $color

Resources you need to complete this tutorial:

Installing Ruby

Before you can be able to test how SASS works, you need to download Ruby to your computer. Launch the Ruby installer and you will be prompted with the Setup page. Select your preferred language and click OK.

1

Then click on I accept the License radio button. 2

Next, install it to your preferred location and make sure that the radio button for Add Ruby executables to your PATH is checked. Click the Install button. This will install the software and when it’s done installing, just click the Finish button.

34

Checking if Ruby is Running Properly

Now that you have installed Ruby, let’s go ahead and check if this is working properly. Open Command Prompt and type the word ruby -v. And you can see, it would return the current version of the Ruby installed along with the date. If it’s returning an error, it could be that Ruby was not installed correctly or you did not put the Ruby executable into your path.

5

Installing SASS

To install SASS, open Command Prompt and type the word gem install sass and you can see that the Installation Prompt that it was successfully installed.

6

Preparing the Necessary Files

Before digging in with SASS, we need to prepare the necessary file you need before you code. Create a new folder to your preferred location (for this tutorial, I placed mine on my desktop) and name it SASS or any name you preferred. Inside the SASS folder, create an HTML file and name it index.html. For the HTML content put the following code.


Introduction to SASS
        	<link href="style.css" rel="stylesheet" type="text/css" /></pre>
<div id="container"><header>
<h1>Sass Sample Document</h1>
<h2>A 1stwebdesigner tutorial</h2>
</header>
<div>
Simple paragraph of text

Another paragraph of text</div>
<div>
<ul id="list1">
	<li>List Item 1</li>
	<li>List Item 2</li>
	<li>List Item 3</li>
</ul>
</div>
<footer>
<h3>This is a cool footer content</h3>
</footer></div>
<pre>

Now for our SASS file, create a new blank file in your text editor and name it style.scss. If you followed the steps, by this time you will have the following file structure.

7

Converting SASS code into CSS code

To convert the SASS code into CSS code, we’re going to use the -watch command in command prompt. This will compile the SASS codes to CSS. Additionally, this will also watch the directories for changes or updates. Let’s try to convert  the SASS file to CSS file. Before we start, we need to put a sample code on our style.scss to see if this working.  Copy and paste the following sample SASS code on the stye.scss file you created under SASS folder.


$myMargin: 0px auto;
$myColor: red;
$myWidth: 600px;

h1 {
	color: $myColor;
	$myMargin: $margin;
}

Next, open your command prompt and then go to the location where you put your files in. In my case, I put it in my desktop so I will type in cd ”Desktop” and it will locate the desktop directory.

8

Now that we are in the desktop file directory, type in the sass –watch Sass:Sass 9

Using –watch command, we will convert all of the .scss files on the folder SASS. It will also watch for the changes or updates on the file. Notice that there are two SASS, divided by a colon. The first one represents the current location of the .scss file while the second one represents the location of the output of the file. Make sure you link the converted CSS file to your HTML file to see this working.

 10

Using Variables

SASS variables are declared using the $ character and are defined like CSS values. Using SASS, you can declare variables for styles like font size, margin, padding and so on. Using variables and giving it a style value makes it easy to reuse a style repeatedly.

There are six different types of variables you can use with SASS.

  1. Strings (e.g. $myString: “your text here”;)
  2. Numbers (e.g. $myNum: 10px;)
  3. Colors (e.g. $myColor: white;)
  4. Booleans (e.g. $myBool: true;)
  5. Lists (e.g. $myItemList: 1px solid red;)
  6. Nulls (e.g. $myVar: null;)

Let’s put some of these types into practice. Open up your style.scss file and type the following code.


$myColor: #009a82;
$myString: " some text here ";
$myFontSize: 13px;
$myMargin: 0px auto;
$myWidth: 460px;

h1 {
	color: $myColor;
	margin: 0;
	padding: 0;
}

#container {
	width: $myWidth;
	margin: $myMargin;
}

Now when you run this code into your browser, you will have this output.

12

Nesting

SASS also allows you to define nested styles. This will let you write easy-to-read codes. For instance, you have the following CSS code.

#container p {
   font-family: Arial;
   font-size: 13px;
}

#container h1 {
   font-family: Tahoma;
   font-size: 15px;
}

#container h2 {
   font-family: Helvetica;
   font-size: 14px;
}

For the SASS version, you will have a format like this.

$myFontsize1: 13px;
$myFontsize2: 18px;
$myFontsize3: 25px;
$myWidth: 500px;
$myMargin: 0px auto;

#container {
    width: $myWidth;
	margin: $myMargin;

	p {
		font-family: Arial;
		font-size: $myFontsize1;
	}

    h1 {
		font-family: Tahoma;
		font-size: $myFontsize3;
	}

	h2 {

		font-family: Helvetica;
		font-size: $myFontsize2;
}
}

Notice that we put all of the elements styles under the id container, instead of naming them one by one under the same element. If you run this code into your browser, you will have something like this.

12

Mixins

Mixins let you define common properties once then re-use them over and over again. Mixins are defined using @mixin directive and contains a block of codes and then reuse them using @include directive. Let’s put this into practice. Copy the code below to your style.scss file.

@mixin border {
   border: 1px solid red;
}

#container {
   width: 960px;
   margin: 0 auto;
   @include border;
}

As you can see, we use the @mixins directive to create a style for border and then we include the style to id container using @include directive. If you run this in your browser, you will have the output below.

13

Operators

Performing mathematical operations is one of the best features of pre-processors like SASS, something which you can’t do with just a normal CSS code. Given this feature allows you do more complex and dynamic codes. Let’s take a look at this how it works. Go ahead and open your style.scss file and copy and paste the code below.


$myColor: #aa30ff;
$myPadding: 20px;
$thickness: 1px;
$border: solid red;

#samplepara{
	color: $myColor;
	padding: $myPadding+30;
}

#list1 {
	color: $myColor;
	border: $thickness+5 $border;
}

As you can see, we perform mathematical computations by adding 30px on the padding. We also added border thickness of 5px on the border. If you run this in your browser, you can see the output will look like this.

14

Functions

SASS offers a variety of functions. A good example of this is the color functions where you can manipulate color styles. Check out the series of color functions below.

  1. darken(color, amount)
  2. lighten(color, amount)
  3. saturate(color, amount)
  4. desaturate(color, amount)
  5. alpha(color)

These are just series of examples of functions. To learn more about functions check out the SASS documentation. For now let’s go ahead and try this example to see how SASS functions work. Open your style.scss folder and then copy and paste the code below.


$myColor: #202020;
$myBackground: #e6e6e6;

body {
     background: darken($myBackground, 20%);
}

h1, h2 {
     color: lighten($myColor, 40%);
}

Notice that the color darkens by 20% using the darken function while the H1 lightens, and also the H2 text by 40% using the lighten functions. So if run this in your browser you can see similar output below.

15

SASS Output Formatting

One of the best features of SASS is it offers several options to control how the .scss code is formatted when compiled into CSS. Using the -style option command, we can perform formatting to our compile CSS code. The following are the SASS formatting styles.

Nested Format

Nested style is the default format of SASS. This format gives indention to all of the styles in your compiled CSS file. To see this in action, copy and paste the code below into your style.scss and then open your Command Prompt (make sure you are inside the directory of SASS) and type in SASS –update style.scss . This command will update the formatting for the compiled CSS file using the update command.

16

 Now go ahead and open your compiled style.css file. As I’ve said above all of the styles will have proper indention.

  17

Expanded Format

This is the most user-friendly and readable format as the braces are properly expanded and each property will have its own line. Let’s see this in action. Using the same code above, open your command prompt and type sass –update style.scss –style expanded. Notice that we added –style command this is used to format compiled CSS file to a particular formatting.

18

So if you are going to look at the compiled CSS file on the SASS file, you can see the code formatting is similar to the image below. Notice that each property has its own line. The braces are also fully expanded.

19

Compact Format

This is the compact format output CSS code in a condensed but still readable format. It adds spaces between braces but all in one line. To see how this works using the same code above, open your command prompt and type sass –update style.scss –style compact .

20

If you are going to check the compiled CSS file, you can see something similar to the image below. It is condensed. Each property and style is in one line.

 21

Compressed Format

The compressed format has minimized output. This is suitable for the production environment. This format has more condensed formatting. Using the same code, open your command prompt and type in sass –update style.scss –style compressed .

22

So if you are going to look at the compiled CSS file on the SASS file, you can see code formatting similar to the image below. As you can see, all codes are in one line with no spaces at all. 23

Conclusion

SASS offers a variety of ways to simplify your CSS issues. It allows you to reduce repetition of codes by using variables. SASS is powerful. This can help to improve the workflow of both web designer and web developers. Learn SASS now and discover how it can it help you build professional websites in a fast-paced development. Hope you enjoyed this tutorial and see you again next time.

Sponsored post
soup-sponsored
20:53
Reposted byLegendaryy Legendaryy

January 27 2014

14:00

Simple Yet Important Cross-Browser Styling Tips Everyone Should Know

Many have been searching for cross-browser styling tips that can help them solve their browser compatibility problems. After all, creating a website can be easy but developing one that looks the same on all browsers can be tough. For many years, browser compatibility is one of the hardest parts of web development.

As a web designer/developer, it’s always our goal to give our website visitors better experience on viewing our site. Having a consistent look on every browser leaves a visitor good impression of the site.

cross-browser-styling

If you’ve been developing websites for a long time you might agree with me that IE8 and the Jurassic lower versions of IE are the one of the web designer’s and developer’s nightmare. Given this fact that, there are still people using these versions of IE to view websites.

This is just one of the issues that we might encounter in developing a cross-browser website. The good thing is that we can redesign a site or initiate some good practices to make them compatible and look the same on every browser. In this article, I will show you some cross-browser styling tips and tricks to make your website development easier.

Use CSS Reset

Let’s face the fact that web browsers interpret different default styling for HTML elements. Some browsers have different interpretations towards values for styles like margin and padding.

To fix this issue, adding a CSS reset at the start of your style sheet is a good practice. This will reset all CSS elements. This would also mean that it will start from a zero base, thus, giving you complete control to your style sheet without worrying about the browser’s CSS issues such as margin, padding and alignment.

Eric Meyer has a good set of CSS rules to do this. You might also want to consider Nicolas Gallagher’s Normalize.css, a modern HTML5 ready alternative to CSS resets. After you’ve linked the CSS rules to your markup, you can now make sure that you have a starting zero base CSS on every browser.

Validate Your HTML and CSS

Before running or publishing your website, it’s a good practice if you validate both your HTML and CSS using validators as it will correct some minor errors that might give you some problems in the future.

You can use W3C HTML Validator and CSS Validator. These are trusted validators by W3C but feel free to use your own tools if you have another resource of HTML and CSS Validator that works for you.

IE Conditional Comments

The Jurassic versions of IE had been giving web designers and developers a headache when it comes to compatibility issues. As an answer to this issue, Microsoft developed conditional comments in their browser that allows linking a style sheet that will be interpreted by IE alone. Check out the code below.

The code below will target all versions of IE.

!
<--[if IE]>
  	<link href="ie.css" rel="stylesheet" type="text/css" /!>
<[endif]-->

The code below will target a specific version of IE.

!
<--[if IE6]>
  	<link href="ie.css" rel="stylesheet" type="text/css" /!>
<[endif]-->

Use Vendor Prefixes

W3C standards are continually evolving. It’s good practice that you know certain drawbacks if a browser supports a particular CSS property. Styles like rounded corners, drop shadows and gradients can now be implemented using CSS alone without the use of images.

Using vendor prefixes will save you a lot of time without worrying if the browser supports your CSS.

Check out the following list of vendor prefixes.

1. Safari and Chrome (-webkit-)
2. Firefox (-moz-)
3. Opera (-o-)
4. Internet Explorer (-ms-)

As an example, let us use the transition property along with vendor prefixes to target specific browsers.


-webkit-transition: all 4s ease;
-moz-transition: all 4s ease;
-ms-transition: all 4s ease;
-o-transition: all 4s ease;
transition: all 4s ease;

Clear Your Floats

We all know how to float elements either to the left or right by using the style property float. By default, if you only just use onefloat along with a non-floated element, it will just flow along the side of the element you floated.

But that is not the issue here; most often we float divs to the left and right and wraps them with a container or wrapper. Consider the images below.

This image shows what we are trying to achieve.

This image shows what we are trying to achieve.

But instead our divs end up like this image.

But instead our divs end up like this image.

This issue can be solved by simply clearing the float using the CSS property clear and adding a value of both. That means both floats will be clear.

Font Size Measurement

Although there are no fixed thumb rules what font size measurement to use, I would recommend using ems (em) and percentages (%) since ems and percentages are based on the default preference set in the user’s browser.

Most people use pixels or points, which are measurements based on the resolution of the screen. This is always fixed.

Regardless your preference, this How to Size Text in CSS article would help you learn more about text in CSS.

Always Test Your Website Using Different Browsers

You might feel lazy testing your website in different browsers, thinking that it looks good in the modern browsers, believe me, I’ve been there but not doing it might give your website visitors a bad experience.

Using an emulator like spoon plugin might save you some time but it is highly recommended if you test your creation directly on the actual browser itself.

Code Simply

Coding simply makes the whole workflow easier and faster. What do I mean? Just by using simple elements in building up your website makes the browser’s task a lot easier to read your site.

As an example, instead of using tables or paragraphs in creating navigation you might just use an unordered list to form the navigation. In creating a responsive site, instead of using tables, divs works perfectly. Keep it simple, organize your codes and name them properly. Believe me, this will save you a lot of time and headache when you run into some problems.

Polishing Off

There are more good tips and tricks out there about cross browser compatibility but this should guide you on the basic foundation in creating a firm cross-browser experience.

It’s a good idea taking some time to read your codes and check them across different browsers. If you know some more tricks and tips that we’ve not listed here or you have some comments or suggestions, I would love to hear from you. Please free to drop them in the comment section below.

January 17 2014

18:28

Better Responsive Images With the Element

This article will introduce you to <picture>, a new proposed element created to try and solve the problem of serving the version of content images which better suits the device currently visiting a web page.


Why Do We Need a New Element?

Responsive Web Design (RWD) has taken web developers and designers by storm, changing the way they approach the development of a website. When talking about RWD, I love to make an analogy. We, as people involved in software development, are always excited by new tools in the same way a child is thrilled by a new toy (you’ve heard of the recent diatribe on front-end automation tools, haven’t you?). We are so intrigued by new toys that sometimes we use, and even develop, tools that don’t resolve a real issue. Well, RWD isn’t like a new toy that everybody loves to play with, without a good reason. It’s a methodology that helps us solve real problems: adapting a website for a great variety of screens. However, as many (all?) things in life, it isn’t perfect and has some limitations.

One of the most important open issues is serving content images for an almost infinite range of devices, trying to serve the version that better suits the specific device currently visiting our website. For those of you who don’t know what content images are, they are the images part of the content. Therefore, they should be shown using the <img> tag and not a CSS rule such as background-image. So far, three main proposals were made, discussed, rejected, and even resurrected (as the picture element). The proposals are: the srcset attribute, the picture element, and the src-n attribute. All of them tried to cover the wider range of use cases possible but, unfortunately for us, none of them have been completely welcomed by all the actors involved. At the time of this writing, it seems that <picture> will be the way to go due to the positive comments on the revamped proposal by representatives of the main browsers. What I mean by revamped, is that the original proposal has been updated incorporating some features of the src-n attribute proposal.

Considering that based on the latest statistics of HTTPArchive.org, images constitute about the 62% of the total weight of web page, you can easily understand that solving the problem of content images is a primary issue, and the sooner we arrive to a solution, the better. In fact, an improvement in how and what images are served will lead to faster loading of websites, which in turn will lead to an improvement of the experience of the websites’ users.

Important Note

Before going ahead, I want to stress that this is still a proposal, hence the specifications are in a state of flux, and nobody can assure you that <picture> will reach the final stage. In addition, being a proposal at an early stage, no browsers offer support for it. For this reason, I strongly suggest you to follow this discussion, read the specifications from time to time, and wait until this proposal reaches a more stable state.


What’s the <picture> Element?

Citing the specifications, “the picture element is intended to give authors a way to control which image resource a user agent presents to a user, based on media query and/or support for a particular image format”. It, “should be used when an image source exists in multiple densities, or when a responsive design dictates a somewhat different image on some types of screens (“art direction”)”.

The proposed element is made of several pieces that we’re going to analyze in detail. The first fact you need to know is that it’s nothing but a container for other elements where we’ll actually specify the different versions of the image we want to show. Inside a picture element you can find two tags: <source> and <img>. The latter is used to provide backward compatibility for older browsers or, in general, for browsers who don’t support it. The source element has three attributes available:

  • srcset: Here is where we specify the URL of the image we want to show. The attribute allows for multiple URLs separated by a comma. In addition, taking cue from the srcset attribute proposal, we can pair each URL with a screen resolution or a width (considered as a min-width rule) specification. The latter is separated from the URL by a space.
  • media: Here we write a media query that, if evaluated to true, will suggest to the UA to show the image specified in the srcset attribute.
  • sizes: The attribute where we specify the set of intrinsic sizes for the sources described in the srcset attribute. It accepts multiple sizes separated by a comma.

Until now, we’ve spent too much time talking and seen nothing concrete. Let’s fix this by seeing some code!

The <picture> in Action

As our first example, let’s say that we developed a website with a mobile-first approach. Now, we want to show a content image and render the image “mobile.png” by default, the image “tablet.png” if the user screen is at least 480px, and “desktop.png” if the user screen is at least 1024px. Because we’re smart developers, we also want to render the image “tablet.png” for those browsers who don’t understand the picture element. To achieve this goal, we have to write the following code:

<picture>
   <source srcset="mobile.png">
   <source media="(min-width: 480px)" srcset="tablet.png">
   <source media="(min-width: 1024px)" srcset="desktop.png">
   <img src="./Better_responsive_image_with_the_picture_element_files/tablet.png" alt="A photo of London by night">
</picture>

In the code above, we’ve adopted pixels as the unit for the media queries, but you can use em as well if you prefer.

The first example shown was quite straightforward. Let’s see how we can made it more sophisticated using the expressive power of the srcset attribute. For the sake of the example, imagine that in addition to the previous requirements we want to differentiate the images based on the resolution of the screen. The resultant code is listed below:

<picture>
   <source srcset="mobile.png, mobile-hd.png 2x">
   <source media="(min-width: 480px)" srcset="tablet.png, tablet-hd.png 2x">
   <source media="(min-width: 1024px)" srcset="desktop.png, desktop-hd.png 2x">
   <img src="./Better_responsive_image_with_the_picture_element_files/tablet.png" alt="A photo of London by night">
</picture>

As you can see, for each <source> in the code, we’ve specified more than one URL into the srcset attribute. The second URL is paired with the string 2x, separated by a space, that targets users with a high-resolution display (pixel density 2x, like the Retina). In this case, the browsers will firstly search for the source element that best accommodates the user screen based on the media query specified (if any). Then, it’ll look at the screen resolution and choose the best fit among the images specified in the srcset attribute.

As our last example, we’ll see how we can employ the sizes attribute. Let’s say that we want our image to cover all the width of the device (100% of the width), regardless of its actual size and pixel density. To achieve this goal, we can specify the size we want to cover and the size of each image in the srcset attribute as shown below:

<picture>
   <source sizes="100%" srcset="mobile.png 480w, small-tablet.png 768w, tablet.png 968w, desktop.png 1024w">
   <img src="./Better_responsive_image_with_the_picture_element_files/tablet.png" alt="A photo of London by night">
</picture>

In this case, the User Agent will automatically calculate the effective pixel density of the image and choose which one to download accordingly.


Browser Compatibility

None. “Hey Aurelio, what do you mean by none? I was already starting to update my website!” If you recognize yourself in this sentence, I’m sorry to disappoint you. As I said multiple times in this article, the picture element is still a proposal and in a very early stage. So, you have to wait for a while before having the chance to employ it. Not all is lost, though. Scott Jehl created a polyfill for this proposal called picturefill. The latter was developed several months ago but has been updated several times to accommodate the specifications. Currently, it isn’t updated to the latest specifications, so its syntax is different than the one described in this article. However, you can still take a look at it and maybe make a Pull Request to help the project.


Conclusions

In this article we discussed the issue of serving content images suitable for the device currently visiting a website. Then, we delved into the specifications of the picture element, the proposal that seems to have succeeded in conciliating browser vendors, developers, and all the actors involved in the process. Unfortunately for us, it’s in a very early stage, so we can’t employ it in our next projects. Nonetheless, I’m confident that browser vendors will start to implement it soon. As a final note, I strongly encourage you to read and follow the specifications.

January 13 2014

14:00

Jimmy Neutron and The Anatomy of the Atomic Design

If Jimmy Neutron were real, could he become a pretty decent web designer? Of course, he would.  For starters, he knows the anatomy of the Atomic Design. He could be designing the best web pages you will ever see, and make your eyes shed blood out of extreme admiration of his designs. And you’ll probably wonder why he is that good.

Well, for one thing, Jimmy Neutron understands a fundamental yet commonly unappreciated principle in web design. He knows how to work on a very potent tool to his full advantage. Using this tool, he could easily design mock-ups and code them without difficulty.

And you know what, you don’t need to have a three-digit IQ to do that. You won’t even need any intricate knowledge of quantum physics for that matter. You just need to have an open mind and some resources. In fact, you just need the basic knowledge of the average guy. Yes, an average web designer with enough creative juices. You just need to master the principle of the Atomic Design. Yes, you read it right, and no, you are not in a physics or chemistry class- the secret is Atomic Design.

From Brad Frost (http://bradfrostweb.com)

From Brad Frost (http://bradfrostweb.com)

Atomic Design is the logical arrangement of design elements into groups for easy organization. To put it in simpler terms, we learned in high school that atoms compose every piece of matter. These atoms, when combined together, form molecules, which ultimately make up the entirety of the universe. In computer language, Atomic Design is basically the method of breaking the interface into smaller components. It is to understand how each part of the page works and how can it be mixed with other elements. These elements are, as we all know, the life and blood of the whole web page.

In this design, developers could style and separate the rudimentary modules like placeholders, inputs, text boxes and combine them into a single bunch. This methodology can be applied to elements like navigation sections, text and icons, and anything that is more likely to be used with regularity. This will most likely improve the speed to a more efficient workflow in coding and designing. This will also prevent designers and coders to be sick and tired of their jobs because everything seems so cyclical.

Basically, the Atomic Design is used to deliver a quick, easy and clear method of creating design systems. Designers could use the concepts of the Atomic Design to make their clients understand how the website will flow and how will it look like. It gives designers the ability to make the abstract concrete, make the intangible, tangible, the unreal, real and the impossible, possible. This leads to designers being able to create consistent, scalable and responsive pages.

Methodologically, Atomic Design has five levels:

  1. Atoms
  2. Molecules
  3. Organisms
  4. Templates
  5. Pages

Atoms

Atoms are the most fundamental building blocks of matter. Without them, nothing will probably exist. Similarly, in the realm of page design, atoms are the building blocks. They are the ‘little guys’ who make up the whole page. Individually, they count as seemingly senseless codes, but together, these little guys can rock worlds. With a single code missing, the whole design will fall. Want me to prove it? Well, you might remember that one night when you are coding a page and something’s not working. Something like an image that is not showing up. Remember how you relentless uttered “Why didn’t I see that” because, after hours of looking at your apparently perfect code, you realize that there was a stray ‘</’ symbol in the way? That’s how these little guys can mess you up, so don’t underestimate them.

Examples of atoms in web interfaces are the HTML tags like ordered and unordered lists, links, labels, inputs and buttons.  Design elements like color palettes, fonts, images, shapes and many more are also considered atoms.

Molecules

It would be far more exciting for a designer to finally see the design realized in a browser. When your HTML and CSS codes finally match the mock up you have imagined, when you finally see the design you thought of for hours, then, that is something to be happy about. You might not know this consciously, but what you were doing was actually combining atoms together!

Molecules are the combination of atoms, (which in our case, design elements) on a page. Example, when a form label, an input or a button is taken as single individuals, they will not make any sense. They will just be codes that are floating to the vast randomness, but once you combine them, they start to be something good. The form, label, input and button suddenly become a search box.

Organisms

Combined together, molecules form up organisms. These organisms are extremely complicated than those simple molecules which make them. The elements of the page combined together, for a specific function and in a specific location could be considered an organism. They are the particular sections in web interface.

Organisms are composed of varying and similar molecules. The variety and similarity give dynamism to the design. An organism cannot just be made up of images or colors alone. They are an excellently crafted juxtaposition of elements, all aimed to beautifying the whole design. For example, a company logo, a navigation bar, a search form and contact links are placed in a single masthead organism because their specific function is to act as the primary means of navigating through the web page.

Tip from Brad Frost http://bradfrostweb.com

“Building up from molecules to organisms encourages creating standalone, portable, reusable components.”

From sbrinzo.deviantart.com

From sbrinzo.deviantart.com

Templates

Templates are not physical nor chemical jargon. They may be off-track to the analogy, but they are basically with a purpose. A template is a tangible formation of organisms performing different roles. They are like families or communities of web elements woven together to form web pages. With templates, web designers are now starting to see clearly what comes out of their efforts.

What’s good with templates is, unlike atoms, molecules and organisms, they are concrete. Meaning, they could be presented to the clients without any fear of being shouted at. Of course, if you are working for a specific organization, you would never, even in your most drunken night, present a template which is composed of a single atom. Your boss would probably roast you alive. You will, of course, present him a tangible design. He needs to see the page in a nutshell. Unless, he won’t hire you ever again. Trust me.

Pages

Pages are the real thing. If in the templates, you are tentatively substituting elements in lieu of the real content, pages have the real content. This is the final level of the design, where everything needs to be real. This is to condition the mind of client about what the viewer sees as it should be.

At this level, all the efforts of the collected atoms will see their fulfillment. This will manifest all the elements working and jiving together to give the user an experience of a lifetime.

Conclusion

The Atomic Design methodology is not formulated to eradicate your daily workflow. It means to improve it. Having a faster, more efficient and better workflow is as good as getting a promotion. That said, you don’t have to be Jimmy Neutron to try this kind of approach, so what harm could you possibly have?

December 20 2013

18:50

Intro to Shadow DOM

Take any modern web page and you will notice that it invariably contains content stitched together from a variety of different sources; it may include the social sharing widgets from Twitter or Facebook or a Youtube video playing widget, it may serve a personalized advertisement from some ad-server or it may include some utility scripts or styles from a third party library hosted over CDN and so on. And if everything is HTML based (as is preferred these days) there is a high probability of collisions between the markup, scripts or styles served from various sources. Generally, namespaces are employed to prevent these collisions which solve the problem to some extent, but they don’t offer Encapsulation.

Encapsulation is one of the pillars on which the Object Oriented Programming paradigm was founded and is normally used to restrict the internal representation of an object from the outside world.

Coming back to our problem, we can surely encapsulate the JavaScript code using closures or using the module pattern but can we do the same for our HTML markup? Imagine that we have to build a UI widget, can we hide the implementation details of our widget from the JavaScript and CSS code that is included on the page, which consumes our widget? Alternatively, can we prevent the consuming code from messing up our widget’s functionality or look and feel?


Shadow DOM to the Rescue

The only existing solution that creates a boundary between the code you write and code that consumes, is ugly – and operates by using a bulky and restrictive iFrame, which brings with itself another set of problems. So are we forced to adapt to this approach always?

Not anymore! Shadow DOM provides us an elegant way to overlay the normal DOM subtree with a special document fragment that contains another subtree of nodes, which are impregnable to scripts and styles. The interesting part is that it’s not something new! Various browsers have already been using this methodology to implement native widgets like date, sliders, audio, video players, etc.

Enabling Shadow DOM

At the time of this writing, the current version of Chrome (v29) supports inspecting Shadow DOM using Chrome DevTools. Open Devtools and click on the cog button at the bottom right of the screen to open the Settings panel, scroll down a bit and you will see a checkbox for showing Shadow DOM.

Turn on Shadow DOM

Now that we have enabled our browser, lets check out the internals of the default audio player. Just type:

<audio width="300" height="32" src="http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg" autoplay="autoplay" controls="controls">
 Your browser does not support the HTML5 Audio.
 </audio>

Into your HTML markup. It shows the following native audio player in supported browsers:

audio_player

Now go ahead and inspect the audio player widget that you just created.

Shadow DOM of Native Date Widget

Wow! It shows the internal representation of the audio player, which was otherwise hidden. As we can see, the audio element uses a document fragment to hold the internal contents of the widget and appends that to the container element ( which is known as Shadow Host ).

Shadow Host & Shadow Root

  • Shadow Host: is the DOM element which is hosting the Shadow DOM subtree or it is the DOM node which contains the Shadow Root.
  • Shadow Root: is the root of the DOM subtree containing the shadow DOM nodes. It is a special node, which creates the boundary between the normal DOM nodes and the Shadow DOM nodes. It is this boundary, which encapsulates the Shadow DOM nodes from any JavaScript or CSS code on the consuming page.
  • Shadow DOM: allows for multiple DOM subtrees to be composed into one larger tree. Following images from the W3C working draft best explains the concept of overlaying the nodes. This is how it looks before the Shadow Root’s content are attached to Shadow Host element:
    Normal Document Tree & Shadow DOM Subtrees

    When rendered, the Shadow tree takes place of Shadow Host’s content.

    Composition Complete

    This process of overlaying the nodes is often referred to as Composition.

  • Shadow Boundary: is denoted by the dotted line in the image above. This denotes the separation between the normal DOM world and the Shadow DOM world. The scripts from either side cannot cross this boundary and create havoc on the other side.

Hello Shadow DOM World

Enough chit-chat I say, Let’s get our hands dirty by writing some code. Suppose we have the following markup, which shows a simple welcome message.

<div id="welcomeMessage">Welcome to My World</div>

Add the following JavaScript code or use this Fiddle:


var shadowHost = document.querySelector("#welcomeMessage");
var shadowRoot = shadowHost.webkitCreateShadowRoot();
shadowRoot.textContent = "Hello Shadow DOM World";

Here we create a Shadow Root using the webkitCreateShadowRoot() function, attach it to a Shadow Host and then simply change the content.

Notice the vendor-specific prefix webkit before the function name. This indicates that this functionality is currently supported on some webkit-based browsers only.

If you go ahead and run this example in a supported browser, then you would see “Hello Shadow DOM World” instead of “Welcome to My World” as the Shadow DOM nodes have over-shadowed the normal ones.

Disclaimer: As some of you may notice, we’re mixing the markup with scripts, which is generally not recommended and Shadow DOM is no exception. We have deliberately avoided the use of templates so early in the game in order to avoid any confusion. Otherwise Shadow DOM does provide an elegant solution to this problem and we will get there pretty soon.


Respecting Shadow Boundary

If you try and access the content of the rendered tree using JavaScript, like so:

var shadowHost = document.querySelector("#welcomeMessage");
var shadowRoot = shadowHost.webkitCreateShadowRoot();
shadowRoot.textContent = "Hello Shadow DOM World";

console.log(shadowHost.textContent);
 // Prints "Welcome to My World" as the shadow DOM nodes are encapsulated and cannot be accessed by JavaScript

You will get the original content “Welcome to My World” and not the content which is actually rendered on the page, as the Shadow DOM tree is encapsulated from any scripts. This also means that the widget that you create using Shadow DOM is safe from any unwanted/conflicting scripts already present in the page.

Styles Encapsulation

Similarly, any CSS selector is forbidden to cross the shadow boundary. Check the following code where we have applied red color to the list items, but that style is only applied to the nodes which are part of the parent page, and the list items which are part of Shadow Root are not affected with this style.

<div class="outer">
  <div id="welcomeMessage">Welcome to My World</div>
  <div class="normalTree">Sample List
  <ul>
      <li>Item 1</li>
      <li>Item 2</li>
  </ul>
  </div>
</div>
<style>
   div.outer li {  
      color: red;  
   } 
   div.outer{  
      border: solid 1px;  padding: 1em; 
   }
</style>
<script type="text/javascript">
    var shadowHost = document.querySelector("#welcomeMessage");
    var shadowRoot = shadowHost.webkitCreateShadowRoot();
    shadowRoot.innerHTML = ["<div class='shadowChild'>",
                            "Shadow DOM offers us Encapsulation from",
                            "<ul>",
                            "<li>Scripts</li>",
                            "<li>Styles</li>",
                            "</ul>",
                            "</div>"
                            ].join(',').replace(/,/g,"");
</script>

You can see the code in action on Fiddle. This encapsulation applies even if we reverse the direction of traversal. Any styles which are defined inside the Shadow DOM does not affect the parent document and remains scoped to the Shadow Root only. Check this Fiddle for an example, where we apply the blue color to list items in Shadow DOM but the parent document’s list items are unaffected.

There is however one notable exception here; Shadow DOM gives us the flexibility to style the Shadow Host, the DOM node which is holding the Shadow DOM. Ideally it lies outside the Shadow boundary and is not a part of Shadow Root, but using the @host rule, one can specify the styles that can be applied to Shadow Host as we have styled the welcome message in the example below.

<div id="welcomeMessage">Welcome to My World</div>
<script type="text/javascript">
  var shadowHost = document.querySelector("#welcomeMessage");
  var shadowRoot = shadowHost.webkitCreateShadowRoot();
  shadowRoot.innerHTML = ["<style>",
                          "@host{ ",
                             "#welcomeMessage{ ",
                                "font-size: 28px;",
                                "font-family:cursive;",
                                "font-weight:bold;",
                             "}",
                          "}",
                          "</style>",
                          "<content select=''></content>"
                          ].join(',').replace(/,/g,"");
</script>

Check this Fiddle as we style the Shadow Host’s welcome message using the styles defined in Shadow DOM.

Creating Style Hooks

As a widget developer, I might want the user of my widget to be able to style certain elements. This is achievable by plugging a hole into the shadow boundary using custom pseudo elements. This is similar to how some browsers create style hooks for the developer to style some internal elements of a native widget. For example, to style the thumb and the track of the native slider you can use the ::-webkit-slider-thumb and ::webkit-slider-runnable-track as follows:


input[type=range]{
    -webkit-appearance:none;
 }
 input[type=range]::-webkit-slider-thumb {
    -webkit-appearance:none;
    height:12px;
    width:12px;
    border-radius:6px;
    background:yellow;
    position:relative;
    top:-5px;
 }
 input[type=range]::-webkit-slider-runnable-track {
    background:red;
    height:2px;
 }

Fork this Fiddle and apply your own styles to it!

Event Re-Targeting

If an event that originates from one of the nodes in Shadow DOM crosses the Shadow Boundary then it is re-targeted to refer to the Shadow Host in order to maintain encapsulation. Consider the following code:


<input id="normalText" type="text" value="Normal DOM Text Node" />
<div id="shadowHost"></div>
<input id="shadowText" type="text" value="Shadow DOM Node" />
<script type="text/javascript">
    var shadowHost = document.querySelector('#shadowHost');
    var shadowRoot = shadowHost.webkitCreateShadowRoot();
    var template = document.querySelector('template');
    shadowRoot.appendChild(template.content.cloneNode(true));
    template.remove();
    document.addEventListener('click', function(e) { 
                                 console.log(e.target.id + ' clicked!'); 
                              });
</script>

It renders two text input elements, one via Normal DOM and another via Shadow DOM and then listens for a click event on the document. Now, when the second text input is clicked, the event is originated from inside Shadow DOM and when it crosses the Shadow Boundary, the event is modified to change the target element to Shadow Host’s <div> element instead of the <input> text input. We have also introduced a new <template> element here; this is conceptually similar to client-side templating solutions like Handlebars and Underscore but is not as evolved and lacks browser support. Having said that, using templates is the ideal way to write Shadow DOM rather than using script tags as has been done so far throughout this article.


Separation of Concerns

We already know that it’s always a good idea to separate actual content from presentation; Shadow DOM should not embed any content, which is to be finally shown to the user. Rather, the content should always be present on the original page and not hidden inside the Shadow DOM template. When the composition occurs, this content should then be projected into appropriate insertion points defined in the Shadow DOM’s template. Let’s rewrite the Hello World example, keeping in mind the above separation – a live example can be found on Fiddle.

<div id="welcomeMessage">Welcome to Shadow DOM World</div>
<script type="text/javascript">
    var shadowRoot = document.querySelector("#welcomeMessage").webkitCreateShadowRoot();
    var template = document.querySelector("template");
    shadowRoot.appendChild(template.content); 
    template.remove();
</script>

When the page is rendered, the content of the Shadow Host is projected into the place where the <content> element appears. This is a very simplistic example where <content> picks up everything inside the Shadow Host during composition. But it can very well be selective in picking the content from Shadow Host using the select attribute as shown below

<div id="outer">How about some cool demo, eh ?
    <div class="cursiveButton">My Awesome Button</div>
</div>
<button>
  Fallback Content
</button>
<style>
button{ 
   font-family: cursive;  
   font-size: 24px;
   color: red; 
}
</style>
<script type="text/javascript">
    var shadowRoot = document.querySelector("#outer").webkitCreateShadowRoot(); 
    var template = document.querySelector("template"); 
    shadowRoot.appendChild(template.content.cloneNode(true));
    template.remove();
</script>

Check out the live demo and play with it to better understand the concept of insertion points and projections.


Web Components

As you may already know, Shadow DOM is a part of the Web Components Spec, which offers other neat features, like:

  1. Templates – are used to hold inert markup, which is to be used at a later point in time. By inert, we mean that all the images in the markup are not downloaded, scripts included are not present until the content of the template actually becomes a part of the page.
  2. Decorators – are used to apply the templates based on CSS Selectors and hence can be seen as decorating the existing elements by enhancing their presentation.
  3. HTML Imports – provides us with the capability to reuse other HTML documents in our document without having to explicitly make XHR calls and write event handlers for it.
  4. Custom Elements – allows us to define new HTML element types which can then be used declaratively in the markup. For example, if you want to create your own navigation widget, you define your navigation element, inheriting from HTMLElement and providing certain life-cycle callbacks which implement certain events like construction, change, destruction of the widget and simply use that widget in your markup as <myAwesomeNavigation attr1="value1"..></myAwesomeNavigation>. So custom elements essentially give us a way to bundle all the Shadow DOM magic, hiding the internal details and packages everything together.

I wont babble much about other aspects of the Web Components Spec in this article but it would do us good to remember that together they enable us to create re-usable UI widgets which are portable across browsers in look and feel and fully encapsulated by all the scripts and styles of the consuming page.


Conclusion

The Web Components Spec is a work in progress and the sample code included which works today may not work on a later release. As an example, earlier texts on this subject use the webkitShadowRoot() method which no longer works; Instead use createWebkitShadowRoot() to create a Shadow Root. So if you want to use this to create some cool demos using Shadow DOM, it’s always best to refer to the spec for details.

Currently, only Chrome and Opera supports it so I would be wary about including any Shadow DOM on my production instance, but with Google coming out with Polymer which is built on top of Web Components and Polyfills coming out to support Shadow DOM natively, this is surely something that every web developer must get his hands dirty with.

You can also stay updated with the latest happenings on Shadow DOM by following this Google+ Channel. Also checkout the Shadow DOM Visualizer tool, which helps you to visualize how Shadow DOM renders in the browser.

December 17 2013

14:00

How to Create a Scrolling Parallax Website

Parallax websites are one of the latest and biggest trends on the web for some time now. If you want to impress your clients or implement immediate impact on your site, this is a good choice for you. In this tutorial, I’ll teach you how to create a simple but beautiful parallax website that will create an illusion of 3D depth to your site. It will surely catch your viewers’ attention. So let’s dig in.

Introduction to Parallax

According to Wikipedia, Parallax came from the Greek word παράλλαξις (parallaxis) meaning, “alteration”. It is the displacement or the difference in the apparent position of an object viewed along two different lines of sight. This Parallax scrolling effect became popular back in the days when Nike released its stunning and brilliant design website named “Nike Better World” as support to the athletes around the world. The website had achieved a lot of good reviews from different sites for its amazing Parallax scrolling effects and web design. Parallax has existed since 1980′s and was used in video game titles and later was used on websites. Today, it is one of the most widely-used designs on the modern Web.

Parallax Website Examples

To show you how this Parallax scrolling effect looks like I’ve collected sites that utilize the Parallax scrolling effect. Check out the following examples below.

brokentwill

bettybetty

express

unfold

The Design Concept

Since Christmas Season is just around the corner, we created a Christmas type mock-up design in Photoshop.

parallax

Resources You Will Need to Complete This Tutorial:

File Structure

For our file structure, we will create three folders and one HTML file:

  • index.html – this will serve as our main file. All of our designs will be utilized on this file.
  • js folder – for our JavaScript/jQuery
  • img folder – for our images
  • css folder – for our styling (CSS)

file-folder

The HTML Markup

On our HTML file, we will add first the HTML5 doctype and series of links on our head section. This will include our link to the CSS file and Google fonts links followed by our jQuery library file.

<!DOCTYPE html>
<html lang="en">
  <head>
	   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
       <title>Creating a Simple Parallax Scrolling Website</title>
       <link rel="stylesheet" href="css/style.css"/>
	   <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
       <link href='http://fonts.googleapis.com/css?family=Wellfleet' rel='stylesheet' type='text/css'>
	   <link href='http://fonts.googleapis.com/css?family=Wellfleet' rel='stylesheet' type='text/css'>
	   <link href='http://fonts.googleapis.com/css?family=Arvo:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
	   <link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
	   <link href='http://fonts.googleapis.com/css?family=Goudy+Bookletter+1911' rel='stylesheet' type='text/css'>
	<script>

</head>

Let’s skip the jQuery code and discuss it later. For now, let’s continue with the HTML elements. We will add a header tag with the logo and navigation inside. The navigation will link to the specific slides. Later, we will add a smooth scrolling effect to make it look good.

<body>

<header id="header">
<div>
<div id="logo"><a href=""> PARALLAX </a></div>

<nav id="nav">
	<ul>
	<li><a href="#slide1" title="Next Section" >Slide 1</a></li>
	<li><a href="#slide2" title="Next Section">Slide 2</a></li>
	<li><a href="#slide3" title="Next Section">Slide 3</a></li>
	<li><a  href="#slide4" title="Next Section">Slide 4</a></li>
	<li><a href="#slide5" title="Next Section">Slide 5</a></li>
	</ul>
</nav>
</div>
</header>

Next let’s add the slides. We will put an ID to each slide which corresponds to its sequence. Inside of each slide, we will put a class of content to center the elements.

	<div id="slide1">
		<div>
			<div id="christmas_tree"> </div>
			<div id="snowflakes1"></div>
			<div id="snowflakes2"></div>
            <h2>MERRY</h2>
		    <h1>CHRISTMAS</h1>
		    <div id="divider"> </div>
		     <h3>HAPPY NEW YEAR </h3>
           <div id="ribbon"></div>
	       <div id="new_year"> </div>
		</div>
    </div>

	<div id="slide2">
		<div >
            <div>
		    <h3>“Then the Grinch thought of something he hadn't before! What if Christmas, he thought, doesn't come from a store. What if Christmas...perhaps...means a little bit more!”</h3>
		  <img src="img/dr-seuss.png" align="left"/> <h4>Dr. Seuss </h4>
		</div>
		</div>
    </div>

   <div id="slide3">
		<div>
			   <div>
		       <h3>“I truly believe that if we keep telling the Christmas story, singing the Christmas songs, and living the Christmas spirit, we can bring joy and happiness and peace to this world.”  </h3>
		      <img src="img/norman.png" align="left"/> <h4>Norman Vincent Peale </h4>
		    </div>
		</div>
    </div>

	<div id="slide4">
		<div>
              <div>
		    <h3>“Christmas doesn't come from a store, maybe Christmas perhaps means a little bit more....” </h3>
		  <img src="img/dr-seuss.png" align="left"/> <h4>Dr. Seuss </h4>
		</div>
		</div>
    </div>

	<div id="slide5">
		<div>
           <div>
		    <h3>“My idea of Christmas, whether old-fashioned or modern, is very simple: loving others. Come to think of it, why do we have to wait for Christmas to do that?” </h3>
		    <img src="img/bob.png" align="left"/> <h4>Bob Hope </h4>
		  </div>
		<div id="copyright"><a href="http://www.1stwebdesigner.com/">Copyright 1stwebdesigner.com </a></div>
		</div>

    </div>
</body>
</html>

Now that we already put all of the HTML elements, our site will look like this.

html

The CSS

We need to do our CSS general styling first. Let’s start by adding styles to our body tag as well as H1, H2, and H3 tags. We will set the font “Museo 700” as our fonts for our H1-H3 tags. We will put shadows on each of them.


body{
	margin: 0;
	padding: 0;
	width: 100%;
}

h1 {
    font-family:"Arvo";
	font-weight:normal;
	font-size: 55px;
	text-align: center;
	color: #fff;
	margin: 0;
	padding: 0;
}

h2 {
   font-family:"Arvo";
   font-weight: normal;
   font-size: 40px;
   text-align: center;
   color: #fff;
   margin: 0;
	padding: 0;
}

h3 {
   font-family: Oswald;
   font-weight: normal;
   font-size: 16px;
   text-align: center;
   margin: 5px 0;
	padding: 0;
	z-index: 1;
	position: relative;
}

Next let’s add the other general styling. This will include the positioning of the elements on screens as well as the container of each slides.


.center { margin: 0 auto; }
.content{ margin: 0 auto; width: 960px; }
.clear { clear: both; }

Now let’s go style the header section. We will add an image with a black background and add 60% opacity to the header, which will hold the logo and the navigation. For the logo, we will float it to the left and for the navigation we will float it to the right. 

#header {
	width: 100%;
	background: url('../img/header-bg.png');
	height: 80px;
	position: fixed;
	margin-top: 30px;
}

#nav { width: 410px; float: right; margin-top: 20px; }
#logo a { color: #fff; text-decoration: none; float: left; font-size: 30px; margin-top: 20px; color: #fff; font-family:"Wellfleet"; font-weight: bold; }
#nav ul{
	list-style: none;
	display: block;
	margin: 0 auto;
	list-style: none;
}

#nav li{
	margin-top: 9px;
	float: left;
	padding-left: 21px;
}

#nav li a { color: #fff; opacity:0.6; font-size: 16px; text-decoration: none; font-family: 'Wellfleet'; }
#nav li a.active { color: #fff; opacity:1; border-bottom: 2px solid #fff; }
#nav li a:hover { color: #fff; opacity:1;  }

Then, let’s add styles to our quotes, author and images as well as to the quotes container.

.quotes {
 font-family: 'Goudy Bookletter 1911', serif;
   font-weight: normal;
   font-size: 30px;
  text-align: left;
  margin: 50px auto;
}

 .author_name_white { font-family:"Wellfleet";  margin: 70px 0 0 75px; color: #fff; font-size: 20px; }
 .author_name_gray { font-family:"Wellfleet";  margin: 70px 0 0 75px; color: #94a4a4; font-size: 20px; }
 .quotes_container { width: 800px; margin: 0 auto; }
#christmas_tree { background: url('../img/christmas-tree.png')no-repeat; width: 48px; height: 77px; margin: 0 auto; position: relative; bottom: -35px;}
#divider { background: url('../img/divider.png')no-repeat; width: 300px; height: 35px; margin: 0px auto 27px auto; }
#ribbon { background: url('../img/ribbon.png')no-repeat; width: 251px; height: 48px; margin: 0 auto;  display: block; position: relative; top: -38px; }
#snowflakes1 { background: url('../img/snowflakes.png')no-repeat; width: 24px; height: 21px; margin: 0 auto;  display: block; position: relative; bottom: -54px; left: -102px; }
#snowflakes2 { background: url('../img/snowflakes.png')no-repeat; width: 24px; height: 21px; margin: 0 auto;  display: block; position: relative; bottom: -33px;  right: -100px; }

Each slide will have a background image or white background color with fixed position. We also need to add some padding to each slide to center the elements inside it.


#slide1, #slide2{ width: 100%; }
#slide1{
	background:url('../img/slide1.jpg') 50% 0 no-repeat fixed;
	color: #fff;
	height: 600px;
	margin: 0;
	padding: 200px 0 260px 0;
	background-size: cover;
}

#slide2{
	background-color: #fff;
	color: #333333;
	height: 300px;
	margin: 0 auto;
	overflow: hidden;
	padding: 200px 0;
}

#slide3{
	background: url(../img/slide3.jpg) 50% 0 no-repeat fixed;
	color: #fff;
	height: 600px;
	padding: 170px 0 0 0;
	background-size: cover;
}

#slide4{
	background-color: #fff;
	color: #333333;
	height: 300px;
	padding: 200px 0;
}

#slide5{
	background: url(../img/slide5.jpg) 50% 0 no-repeat fixed;
	height: 200px;
	margin: 0 auto;
	padding: 250px 0;
	color: #fff;
	background-size: cover;
}

Lastly, we will style our copyright text and center it to the screen.

#copyright  { color: #fff; font-family:"Wellfleet";  font-size: 14px; margin-top: 100px; text-align: center;  }
#copyright  a { text-decoration: none; color: #fff;  }

Now that we put all of our CSS styles, the look of our site will look like exactly the same with our PSD design.

The jQuery

Let’s put this Parallax site into life. On the head section, we are going to add the following jQuery codes. Check the Reference URL.

$(document).ready(function() {
$('a[href*=#]').each(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
if ($target) {
var targetOffset = $target.offset().top;
$(this).click(function() {
            $("#nav li a").removeClass("active");
            $(this).addClass('active');
$('html, body').animate({scrollTop: targetOffset}, 1000);
return false;
});
}
}
});

});

On this part of the jQuery code, we’re creating a click event handler to all the links that have “#” symbol anywhere in the href. The very next line, we will check if the link is pointing to the same page by checking for a match between location.pathname and this.pathname. We can then make sure that the link includes a qualified URL or just an identifier.

$(document).ready(function() {
  $('a[href*=#]').each(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
    && location.hostname == this.hostname
    && this.hash.replace(/#/,'') ) {
 var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
 var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
       if ($target) {
 var targetOffset = $target.offset().top;

For this part, when the user click the menu link, it will remove the class active on that current active menu link and add it to that menu link that the user has clicked. This will also scroll to the target div id section.

$(this).click(function() {
            $("#nav li a").removeClass("active");
            $(this).addClass('active');
           $('html, body').animate({scrollTop: targetOffset}, 1000);
           return false;
         });
      }
    }
  });
});

Tips: You can also make the speed of the scrolling effect faster or slower by simply by changing the value of 1000. (1000 means 1000 milliseconds). You might also want to use the value “fast” (200 milliseconds) or “slow” (600 milliseconds). Take note that the default is 400 milliseconds. It depends on what you need or want.

$('html, body').animate({scrollTop: targetOffset}, 1000);

Final Words

Parallax scrolling effects are slowly being implemented on a lot of  sites across the Web. If you take the time to look for more inspiration around the Web, you will see a lot of advance Parallax sites that will blow your mind.

Today I’ve shown you how to do a relatively simple parallax scrolling website; you can play around with it and improve it. Hope you enjoyed this tutorial. Please feel free to leave links, comment or suggest if you learned in this tutorial. Until next time!

December 09 2013

20:49

AbsurdJS or Why I Wrote My Own CSS Preprocessor

As a front-end developer, I’m writing a lot of CSS and using pure CSS is not the most efficient way nowadays. CSS preprocessors are something which have helped me a lot. My first impression was that I finally found the perfect tool. These have a bunch of features, great support, free resources and so on. This is all true and it still applies, but after several projects, I realized that the world is not so perfect. There are two main CSS preprocessors – LESS and SASS. There are some others, but I have experience with only these two. In the first part of this article I’ll share with you what I don’t like about preprocessors and then in the second part I’ll show you how I managed to solve most of the problems that I had.


The Problems

problems

Setup

No matter which CSS preprocessor is involved, there is always setup required, like, you can’t just start typing .less or .sass files and expect to get the .css file. LESS requires NodeJS and SASS Ruby. At the moment, I’m working mostly on HTML/CSS/JavaScript/NodeJS applications. So, LESS seems like a better option, because I don’t need to install additional software. You know, adding one more thing to your ecosystem means more time for maintenance. Also, not only do you need the required tool, but all of your colleagues should now integrate the new instrument as well.

Firstly, I chose LESS because I already had NodeJS installed. It played well with Grunt and I successfully finished two projects with that setup. After that, I started reading about SASS. I was interested in OOCSS, Atomic design and I wanted to build a solid CSS architecture. Very soon I switched to SASS, because it gave me better possibilities. Of course I (and my colleagues too) had to install Ruby.

Output

A lot of developers don’t check the produced CSS. I mean, you may have really good looking SASS files, but what’s used in the end is the compiled .css file. If it is not optimized and its file size is high, then you have a problem. There are few things which I don’t like in both preprocessors.

Let’s say that we have the following code:

// LESS or SASS
p {
    font-size: 20px;
}
p {
    padding: 20px;
}

Don’t you think that this should be compiled to:

p {
    font-size: 20px;
    padding: 20px;
}

Neither LESS nor SASS works like that. They just leave your styles as you type them. This could lead to code duplication. What if I have complex architecture with several layers and every layer adds something to the paragraph. There will be several definitions, which are not exactly needed. You may even have the following situation:

p {
    font-size: 20px;
}
p {
    font-size: 30px;
}

The correct code at the end should be only the following:

p {
    font-size: 30px;
}

I now know that the browser will take care and will find out the right font size. But, isn’t it better to save those operations. I’m not sure that this will affect the performance of your page, but it affects the readability for sure.

Combining selectors which share the same styles is a good thing. As far as I know, LESS doesn’t do this. Let’s say that we have a mixin and we want to apply it to two classes.

.reset() {
    padding: 0;
    margin: 0;
}
.header {
    .reset();
}
.footer {
    .reset();
}

And the result is:

.header {
    padding: 0;
    margin: 0;
}
.footer {
    padding: 0;
    margin: 0;
}

So, these two classes have the same styles and they could be combined into one definition.

.header, .footer {
    padding: 0;
    margin: 0;
}

I was wondering if this is actual performance optimization, and I didn’t find an accurate answer, but it looks like a good thing. SASS has something called place holders. It’s used exactly for such situations. For example:

%reset {
    padding: 0;
    margin: 0;
}
.header {
    @extend %reset;
}
.footer {
    @extend %reset;
}

The code above produces exactly what I wanted. The problem is that if I use too many place holders I may end up with a lot of style definitions, because the preprocessor thinks that I have something to combine.

%reset {
    padding: 0;
    margin: 0;
}
%bordered {
    border: solid 1px #000;
}
%box {
    display: block;
    padding: 10px;
}
.header {
    @extend %reset;
    @extend %bordered;
    @extend %box;
}

There are three place holders. The .header class extends them all and the final compiled CSS looks like this:

.header {
    padding: 0;
    margin: 0;
}
.header {
    border: solid 1px #000;
}
.header {
    display: block;
    padding: 10px;
}

It looks wrong, doesn’t it? There should be only one style definition and only one padding property.

.header {
    padding: 10px;
    margin: 0;
    border: solid 1px #000;
    display: block;
}

Of course, there are tools which may solve this, having the compiled CSS. But as I said, I prefer to use as less libraries as possible.

Syntax Limitation

While I was working on OrganicCSS, I met a lot of limitations. In general, I wanted to write CSS as I write JavaScript. I mean, I had some ideas about complex architecture, but I wasn’t able to achieve them, because the language which I was working with was kinda primitive. For example, let’s say that I need a mixin which styles my elements. I want to pass a theme and border type. Here is how this should look in LESS:

.theme-dark() {
   color: #FFF;
   background: #000;
}
.theme-light() {
   color: #000;
   background: #FFF;
}
.component(@theme, @border) {
   border: "@{border} 1px #F00";
   .theme-@{theme}();
}
.header {
   .component("dark", "dotted");
}

Of course I’ll have a lot of themes and they should also be mixins. So, the variable interpolation works for the border property, but not for the mixin names. That’s a simple one, but it is currently not possible, or at least I don’t know if it is fixed. If you try to compile the above code you will get Syntax Error on line 11.

SASS is one step further. The interpolation works with placeholders, which makes things a little bit better. The same idea looks like this:

@mixin theme-dark() {
   color: #FFF;
   background: #000;
}
@mixin theme-light() {
   color: #000;
   background: #FFF;
}
%border-dotted {
   border: dotted 1px #000;
}
@mixin component($theme, $border) {
   @extend %border-#{$border};
   @include theme-#{$theme};
}
.header {
   @include component("dark", "dotted");
}

So, the border styling works, but the theme produces:

Sass Error: Invalid CSS after "   @include theme-": expected "}", was "#{$theme};"

That’s because the interpolation in the names of the mixins and extends is not allowed. There is a long discussion about that and will probably be fixed soon.

Both LESS and SASS are great if you want to improve your writing speed, but they are far from perfect for building modular and flexible CSS. Mainly, they are missing things like encapsulation, polymorphism and abstraction. Or at least, they are not in the form which I needed.


A New Approach

I fought several days with those limitation. I invested a good amount of time reading documentation. In the end, I just gave up and started looking for other options. What I had wasn’t flexible enough and I started thinking about writing my own preprocessor. Of course, that’s a really complex task and there are a lot of things to think about, such as:

  • the input – normally preprocessors take code which looks like CSS. I guess the idea is to complete the language, such as add in missing, yet necessary features. It is also easy to port pure CSS and the developers could start using it immediately, because in practice, it is almost the same language. However, from my point of view, this approach brings few difficulties, because I had to parse and analyze everything.
  • the syntax – even if I write the parsing part, I had to invent my own syntax which is kind of a complex job.
  • competitors – there are already two really popular preprocessors. They have good support and an active community. You know, most of the coolest things in our sphere are so useful, because of the contributers. If I write my own CSS preprocessor and I don’t get enough feedback and support from the people, I may be the only one which is actually using it.
nocss

So, I thought about it a bit and found a solution. There is no need to invent a new language with a new syntax. It’s already there. I could use pure JavaScript. There is already a big community and a lot of people may start using my library immediately. Instead of reading external files, parsing and compiling them, I decided to use the NodeJS ecosystem. And of course, the most important thing – I completely removed the CSS part. Writing everything in JavaScript made my web application a lot cleaner, because I didn’t have to deal with the input format and all those processes which produces the actual CSS.

(The name of the library is AbsurdJS. You may find this name funny and it is indeed. When I share my idea with some friends they all said, writing your CSS in JavaScript – absurd. So, that was the perfect title.)


AbsurdJS

absurd

Installation

To use AbsurdJS you need NodeJS installed. If you still don’t have this little gem on your system go to nodejs.org and click the Install button. Once everything finishes you could open a new console and type:

npm install -g absurd

This will setup AbsurdJS globally. This means that wherever you are, you may run the absurd command.

Writing Your CSS

In the JavaScript world, the closest thing to CSS is JSON format. So, that’s what I decided to use. Let’s take a simple example:

.content {
    padding: 0;
    margin: 0;
    font-size: 20px;
}
.content p {
    line-height: 30px;
}

This is pure CSS. Here is how it looks like in LESS and SASS:

.content {
    padding: 0;
    margin: 0;
    font-size: 20px;
    p {
        line-height: 30px;
    }
}

In the context of AbsurdJS the snippet should be written like this:

module.exports = function(api) {
    api.add({
        '.content': {
            padding: 0,
            margin: 0,
            'font-size': '20px',
            p: {
                'line-height': '30px'
            }
        }
    });
}

You may save this to a file called styles.js and run:

absurd -s .\styles.js

It will compile the JavasSript to the same CSS. The idea is simple. You write a NodeJS package, which exports a function. The function is called with only one parameter – the AbsurdJS API. It has several methods and I’ll go through them later, but the most common one is add. It accepts valid JSON. Every object defines a selector. Every property of that object could be a CSS property and its value or another object.

Importing

Placing different parts of your CSS in different files is really important. This approach improves the readability of your styles. AbsurdJS has an import method, which acts as the @import directive in the CSS preprocessors.

var cwd = __dirname;
module.exports = function(api) {
    api.import(cwd + '/config/main.js');
    api.import(cwd + '/config/theme-a.js');
    api.import([
        cwd + '/layout/grid.js',
        cwd + '/forms/login-form.js',
        cwd + '/forms/feedback-form.js'
    ]);
}

What you have to do is write a main.js file which imports the rest of the styles. You should know that there is overwriting. What I mean is that if you define a style for the body tag inside /config/main.js and later in /config/theme-a.js use the same property, the final value will be the one used in the last imported file. For example:

module.exports = function(api) {
    api.add({
        body: { margin: '20px' }
    });
    api.add({
        body: { margin: '30px' }
    });
}

Is compiled to

body {
    margin: 30px;
}

Notice that there is only one selector. While, if you do the same thing in LESS or SASS you will get

body {
    margin: 20px;
}
body {
    margin: 30px;
}

Variables and Mixins

One of the most valuable features in preprocessors are their variables. They give you the ability to configure your CSS, such as define a setting somewhere in the beginning of the stylesheet and use it later on. In JavaScript, variables are something normal. However, because you have modules placed in different files you need something that acts as a bridge between them. You may want to define your main brand color in one file, but later use it in another. AbsurdJS offers an API method for that, called storage. If you execute the function with two parameters, you create a pair: key-value. If you pass only a key, you actually get the stored value.

// config.js
module.exports = function(api) {
    api.storage("brandColor", "#00F");
}

// header.js
module.exports = function(api) {
    api.add({
        header: {
            color: api.storage("brandColor")
        }
    })
}

Every selector may accept not only an object, but also an array. So this is also valid:

module.exports = function(api) {
    api.add({
        header: [
            { color: '#FF0' },
            { 'font-size': '20px' }
        ]
    })
}

This makes sending multiple objects to specific selectors possible. It plays very well with the idea of mixins. By definition, the mixin is a small piece of code which could be used multiple times. That’s the second feature of LESS and SASS, which makes them attractive for developers. In AbsurdJS the mixins are actually normal JavaScript functions. The ability to put things inside storage gives you the power to share mixins between the files. For example:

// A.js
module.exports = function(api) {
    api.storage("button", function(color, thickness) {
        return {
            color: color,
            display: "inline-block",
            padding: "10px 20px",
            border: "solid " + thickness + "px " + color,
            'font-size': "10px"
        }
    });
}

// B.js
module.exports = function(api) {
    api.add({
        '.header-button': [
            api.storage("button")("#AAA", 10),
            {
                color: '#F00',
                'font-size': '13px'
            }
        ]
    });
}

The result is:

.header-button {
    color: #F00;
    display: inline-block;
    padding: 10px 20px;
    border: solid 10px #AAA;
    font-size: 13px;
}

Notice, that there is only one selector defined and the font-size property has the value from the second object in the array (the mixin defines some basic styles, but later they are changed).

Plugins

Ok, mixins are cool, but I always wanted to define my own CSS properties. I mean using properties that don’t normally exist, but encapsulate valid CSS styles. For example:

.header {
    text: medium;
}

Let’s say that we have three types of text: small, medium and big. Each of them has a different font-size and different line-height. It’s obvious that I can achieve the same thing with mixins, but AbsurdJS offers something better – plugins. The creation of the plugin is again via the API:

api.plugin("text", function(api, type) {
    switch(type) {
        case "small":
            return {
                'font-size': '12px',
                'line-height': '16px'
            }
        break;
        case "medium":
            return {
                'font-size': '20px',
                'line-height': '22px'
            }
        break;
        case "big":
            return {
                'font-size': '30px',
                'line-height': '32px'
            }
        break;
    }
});

This allows you to apply text: medium to your selectors. The above styling is compiled to:

.header {
    font-size: 20px;
    line-height: 22px;
}

Media Queries

Of course the library supports media queries. I also copied the idea of the bubbling feature (you are able to define breakpoints directly inside the elements and AbsurdJS will take care for the rest).

api.add({
    '.footer': {
        'font-size': '14px',
        '@media all and (min-width: 320px) and (max-width: 550px)': {
            'font-size': '24px'
        }
    },
    '.content': {
        '@media all and (min-width: 320px) and (max-width: 550px)': {
            margin: '24px'
        }
    }
})

The result is:

.footer {
    font-size: 14px;
}
@media all and (min-width: 320px) and (max-width: 550px) {
    .footer {
        font-size: 24px;
    }
    .content {
        margin: 24px;
    }
}

Keep in mind that if you have the same media query used multiple times, the compiled file will contain only one definition. This actually saves a lot of bytes. Unfortunately LESS and SASS doesn’t do this.

Pseudo Classes

For these, you just need to pass in valid JSON. The following example demonstrates how to use pseudo CSS classes:

module.exports = function(api) {
    api.add({
        a: {
            'text-decoration': 'none',
            ':hover': {
                'text-decoration': 'underline'
            }
        }
    });
}

And it is compiled to:

a {
    text-decoration: none;
}
a:hover {
    text-decoration: underline;
}

Integration

AbsurdJS works as a command line tool, but it could be used inside a NodeJS application as well. For example:

var Absurd = require("absurd"),
    absurd = Absurd(),
    api = absurd.api,
    output = "./css/styles.css";

api.add({ ... }).import("...");
absurd.compileFile(output, function(err, css) {
    // do something with the css
});

Or if you have a file which acts as an entry point:

var Absurd = require("absurd");
Absurd("./css/styles.js").compileFile("./css/styles.css", function(err, css) {
    // do something with the css
});

The library also supports integration with Grunt. You can read more about that on the following Github page.

Command Line Interface Options

There are three parameters available:

  • [-s] – main source file
  • [-o] – output file
  • [-w] – directory to watch

For example, the following line will start a watcher for a ./css directory, will grab ./css/main.js as an entry point and will output the result to ./styles.css:

absurd -s ./css/main.js -o ./styles.css -w ./css

Conclusion

Don’t get me wrong. The available CSS preprocessors are awesome, and I’m still using them. However, they came with their own set of problems. I managed to solve them by writing AbsurdJS. The truth is that I just replaced one tool with another. The usage of this library eliminates the usual writing of CSS and makes things really flexible, because everything is JavaScript. It could be used as a command line tool or it could be integrated directly into the application’s code. If you are interested in AbsurdJS, feel free to check out the full documentation at github.com/krasimir/absurd or fork the repo.

December 02 2013

15:00

10 Creative Loading Effects for Your Website

People hate waiting. It is a fact that web designers and developers should accept. It has been quite a maxim that as designers, we shouldn’t make our viewers wait. This is because many people tend to get bored and choose a website that loads faster. And that, my friend, is a big no-no.

However, waiting is seemingly inevitable. Despite modern internet connection speeds, some browsers still take time to load web elements. So it becomes a need to make people still want to visit your website even if it takes a little bit of time when they load it. There are a lot of plausible solutions for this, and I have to say, that our topic for this article is one of these.

Loading effects are very good tools to keep your viewer in viewing your website. It is not commonly used and that could be an edge. If you don’t want your viewers to wait, then give them something to look at (or do) while they’re waiting.

I know what you’re thinking, where the heck will I find these loading effects? And how can I include them in my website?

Well, that’s why we’re here. We collected 10 of the best website loading effects! Here you go, try these:

1. Creative Loading Effects

loading-effect-tutorials

This tutorial is a thing of beauty. You’ll love this one because it does not showcase a single effect; you can choose from a wide variety of effects. Try and click the demo and play with it.

2. Spinning Loading

loading-effect-tutorials-01

With bold red words written ‘Loading’ in it, this snippet is also a creative way of letting your viewers wait. It is clean-looking and relatively easy to use.

3. Planets

loading-effect-tutorials-02

It’s both peculiar and cool to see these planets dancing. This effect could be very good for websites which adapts a cutey-patootsy layout.

4. Sinister Loadscreen

loading-effect-tutorials-09

Yes, this loading effect seems sinister and dark. But it’s a good effect to intrigue your readers by shrouding your website with some sort of cryptic and evil.

5. Yet Another Loading Animation

loading-effect-tutorials-06

This loading animation is simple and yet full of movement. You’ll love the rhythm of its motion. Perfect for music-oriented websites!

6. CProgress

loading-effect-tutorials-03

Cprogress uses JQuery to magnificently show a very cool and easy to use loadscreen. Be awed as you tinker into these lines of code because they are fully customizable!

7. Spin.js

loading-effect-tutorials-04

Spin.js will make your world and imagination spin! Using sliders, you can easily customize how you want your loadscreen to be. Perfect for Mac and Windows 8 lovers.

8. Alessio Atzeni

loading-effect-tutorials-05

This guy’s cool tutorial is very easy to follow since it uses CSS3 and HTML only. It also comes in three different templates to choose from.

9. Facebook-ish Loading Animation

loading-effect-tutorials-07

If you want your website to look like Facebook, this loading effect will be a great help. It adapts the Facebook load effect (the one that shows up when you load photos).

10. Flickr Style

loading-effect-tutorials-08

Here’s one for the Flickr lovers! You’ll love to put this in your website because the effect looking simple and edgy.

Conclusion

With the ten effects you just saw, waiting could never be as bad as web designers think it to be. In fact, your viewers will find it otherwise. They will love your website because even at the moments where they have to wait, they could readily feel the creative juice you just gave in for your beloved website.

September 23 2013

17:50

Mobile First With Bootstrap 3

Ok so a couple of weeks now, on it’s very own two year anniversary Mark Otto and the rest of the guys responsible for the develop and maintenance of Bootstrap announced the official release of the framework’s third version, and it came on steroids, let’s see what we’re getting.


What’s New?

First off, the most important changes you’re going to find in the new Bootstrap release is the support for responsive websites, as a matter of fact the responsive module has been removed. Now, from its core, Bootstrap is responsive, more than that, this new version comes with the approach of “Mobile First”, meaning that almost everything has been redesigned to start from a lower screen size and scale up (more on that in a bit).

Nearly everything has been redesigned and rebuilt to start from your handheld devices and scale up.

In the look and feel you’ll see a lot of changes too, prominently the fact that the whole style has gone flat, and there’s an optional theme for a 2.0-er look. Additionally, the icons have gone from images to a font, which is really handy to use when needing different sizes and colors.


Grid System

Let’s start talking about the Grid System, oh the Grid, as a matter of fact, there are four Grid Systems in this new version of Bootstrap, each works exactly the same, being differentiated by the screen size width at which they operate.

Enabling the Grid

In order for the Grid System to work properly and also to ensure proper rendering and touch zooming, add the viewport meta tag to your document:

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

Different Width Grids

There are four Grid Systems in this new version of the framework, with the width of the viewport being the parameter that differentiates them. The widths that set the frontiers between one and another are as follows:

  • Extra small devices ~ Phones (< 768px)
  • Small devices ~ Tablets (>= 768px)
  • Medium devices ~ Desktops (>= 992px)
  • Large devices ~ Desktops (>= 1200px)

And each of the different supported viewports have a particular class to address it, as follows:

  • col-xs- ~ Extra small devices
  • col-sm- ~ Small devices
  • col-md- ~ Medium devices
  • col-lg- ~ Large devices

To make use of the Grid System you’d need a container element, with a class "container", and inside a second container with a class "row". Notice how in both cases the “fluid” suffix has disappeared, this in contrast with Bootstrap 2. And inside the second container you’d place your columns.

<div class="container">
    <div class="row">
        <div class="col-xs-6">col-xs-6</div>
        <div class="col-xs-6">col-xs-6</div>
    </div>
</div>
cols-xs

As I mentioned earlier, this new version of Bootstrap comes with a Mobile First approach, what this means is that the columns with a class suffixed with an "xs" are always going to be floated horizontally, no matter the viewport size. If you were to say, use columns prefixed by an "md" and the viewport happened to be less than 992px wide (even 991px), those columns will stack one below the other with a 100% width, as in the next example.

<div class="container">
    <div class="row">
        <div class="col-md-4">col-md-4</div>
        <div class="col-md-4">col-md-4</div>
        <div class="col-md-4">col-md-4</div>
    </div>
</div>

When this page is viewed at a viewport of 992px or more, it will look like this:

cols-md

If you would happen to see that document in a viewport of 991px or less, it would look as follows:

cols-md-stacked

You can also combine classes to address your elements at a given viewport size. For instance, if in the following example you’d need the first two columns floated side by side in small devices (sm) and stacked on phones, you could add the col-sm-6 in addition to the col-md-4 class.

<div class="container">
    <div class="row">
        <div class="col-sm-6 col-md-4">col-sm-6 col-md-4</div>
        <div class="col-sm-6 col-md-4">col-sm-6 col-md-4</div>
        <div class="col-sm-6 col-md-4">col-sm-6 col-md-4</div>
    </div>
</div>

In this case, opening the page in a viewport larger than 991px you’d see three equal columns, one next to the other, just like in the last example. However, if you’d see it in a viewport with a width between 768px and 991px, you’d get the following result:

cols-combined

As in the example above, you can combine and nest columns in a lot of different combinations to create very complex layouts. There’s a lot more to the Grid System in Bootstrap, but going into detail about every aspect of it would take a while to cover, so for a deeper look into it I’d strongly suggest that you go ahead and take a look at the documentation.


Bootstrap CSS

Most of the classes for the Base CSS part of Bootstrap have remained the same, however there are some changes that we must keep in mind when using this new version.

The code as a whole, has being re-written and variable names have changed. If you look at the .less files, you’ll find that all the variables in the framework have switched from camelCase to use hyphens for word separation, and also every variable name has been standardized in a “element-state-pseudo state” approach. What this means is that element-specific styles like:

<ul class="unstyled">...</ul>

Now are prefixed with the element that they are applied to, so in this new version of Bootstrap the previous list would become.

<ul class="list-unstyled">...</ul>

The same applies for lists with an “inline” style applied to them. Some other changes in the variables names reflecting in the classes that we’ve known from the earlier days are those related with size, for instance with buttons, in version 2.* you’d have:

<button class="btn btn-mini"></button>
<button class="btn btn-small"></button>
<button class="btn btn-large"></button>

This size suffixes have changed to match the overall naming convention and this is the same as for the Grid System, so the previous buttons declaration for version three becomes:

<button class="btn btn-xs"></button>
<button class="btn btn-sm"></button>
<button class="btn btn-lg"></button>

The same applies for input sizes and visibility declarations as well.

Responsive Tables

The overall syntax and layout for the tables remain the same in this version of the framework, but, loyal to the whole “Mobile First” paradigm, now we have responsive tables in this iteration of Bootstrap. To take advantage of it, simply wrap the whole table in a container with a class of “responsive-table“, what this will do is make the tables scroll horizontally in small devices (< 768px).

<div class="table-responsive">
    <table class="table">...</div>
</div>

And the resulting table:

responsive-tables

Forms

In the CSS department, it’s in the Forms where you’d see the major differences. For starters, every input in a form in Bootstrap three is now displayed as a “block” element with a 100% width. The “size” attributes you can modify with a class in form controls relate to the padding and font-size of the element and not the width, to control that you’d need to put it in a container of the desired width.

The markup for the forms has also changed, in it’s most basic form, in version 2.* a form would look something like this.

<form>
    <fieldset>
        <legend>...</legend>
        <label for="input">...</label>
        <input type="text" name="input" placeholder="..." >
    </fieldset>
</form>

The markup for the same form in the new version adds an extra element, and a class to the input itself, and goes as follows.

<form role="form">
    <fieldset>
        <legend>...</legend>
        <div class="form-group">
            <label for="input">...</label>
            <input type="text" name="input" class="form-control" placeholder="..." >
        </div>
    </fieldset>
</form>

Bootstrap has been created with Accessibility in mind, that’s the reason for the “role” attribute addition, note also that the label/input combo is wrapped inside a wrapper with a class of “form-group“, and like everything else, this has to do with the responsive nature of the framework.

The search form is gone in this version, and since all inputs and textareas are 100% width by default, special consideration has to be taken with inline forms, however the markup for these is almost identical to that of the previous form.

<form class="form-inline" role="form">
    <div class="form-group">
        <label class="sr-only" for="email">Email address</label>
        <input type="email" class="form-control" placeholder="Enter email">
    </div>
    <div class="form-group">
        <label class="sr-only" for="pass">Password</label>
        <input type="password" class="form-control" placeholder="Password">
    </div>
    <div class="checkbox">
        <label>
            <input type="checkbox"> Remember me
        </label>
    </div>
    <button type="submit" class="btn btn-default">Sign in</button>
</form>
inline-forms

Note the addition of the class “form-inline” to the form element, and that of “sr-only” to the label, this last class has to do with the Accessibility part of the framework. The use of a label is optional with inline forms, however it’s highly encouraged and doesn’t hurt anyone. And by the way, the “sr-only” stands for Screen Reader only. So screen readers will find the label and “say it” to the user.

Lastly, to create a horizontal form you simply set the width of the label by setting it’s “col-md-” or “_sm” or whatever and the corresponding “control-label” class, just as with version two., and then wrap the input in a container with its own column width specified.

<form class="form-horizontal">
    <div class="form-group">
        <label class="col-md-2 control-label" for="email">Email address</label>
        <div class="col-md-3">
            <input type="email" class="form-control" placeholder="Enter email">
        </div>
    </div>
</form>

And the resulting form.

horizontal-forms

There are some other changes that have been made in regard to forms, like the removal of “input-prepend” and “input-append” classes, in favor of “input-group” and “input-group-addon“. However, there’s a lot more to cover yet, so for details on that, please refer to the documentation.

Glyphicons

Another area where you’re going to find major changes is in the framework’s icons. The icon library includes 40 new glyphs, and not only that, they switched from using images to fonts, so now instead of adding the two “glyphicons-*” images to your “img” folder, you’ll have to add the four “glyphicons” fonts to your “fonts” directory, and yes, four of them. This has to do with the browser’s compatibility.

For performance reasons, every icon requires a base class and a icon specific class. So now, to add a user icon you’d use:

<span class="glyphicon glyphicon-user"></span>

The switch from images to fonts, gives control to icon coloring and sizing, and also allows you to replace the default icons with some custom ones you may like. If you happen to wonder where you might find such font icons, Fontello is a great resource.


JavaScript Components

Although redesigned and recreated, the JavaScript Components in Bootstrap 3.0 keep the same names and usage. With a couple of slightly and not that gentle differences.

Modals

Perhaps one of the most used plugins in Bootstrap is Modals. You’ll find it is quite similar, with the differences being that the containers “modal-header”, “modal-body” and “modal-footer” are not wrapped inside a “modal-content” inside a “modal-dialog” container. So what used to be:

<div class="modal hide fade">
    <div class="modal-header"></div>
    <div class="modal-content"></div>
    <div class="modal-footer"></div>
</div>

Changes to:

<div class="modal fade">
    <div class="modal-content">
        <div class="modal-dialog">
            <div class="modal-header"></div>
            <div class="modal-content"></div>
            <div class="modal-footer"></div>
        </div>
    </div>
</div>

Yes, it’s a little more markup, but it improves the responsiveness of the component and also allows it to scroll the whole viewport instead of having a “max-height” parameter.

To trigger them via JavaScript, you’d use the same method as before.

$( '#my-modal' ).modal('show');

The rest of the plugins remain mostly the same. On a special note, the accordion is gone in favor of collapsible panels, they work pretty much the same and have a very similar syntax. With some classes changing a bit, they still require the transitions plugin and don’t require any extra containers.

Also, the Typeahead plugin has disappeared from Bootstrap in favor of Twitter’s Typeahead plugin.

Events

JavaScript events are now namespaced, but what does mean to you? Well, in Bootstrap two, to listen for the moment when some alert in your site was “close“, you’d add:

$( '#my-alert' ).bind( 'close', function() {});

Now in this third version, the event name has changed, it is namespaced to the framework, so the previous snippet would be:

$( '#my-alert' ).bind( 'close.bs.alert', function() {});

Go ahead and take a look at the rest of the JavaScript Components Bootstrap has to offer (which, are still dependent on jQuery).


New components

There are a couple new components in the CSS part of the framework, list groups and panels.

List Groups

List groups, from the official documentation.

… are a flexible and powerful component for displaying not only simple lists of elements, but complex ones with custom content.

To create a list group simply create an unordered list with a “list-group” class, and add the “list-group-item” to every list item.

<ul class="list-group">
    <li class="list-group-item">Lorem ipsum...</li>
    <li class="list-group-item">Dolor sit...</li>
</ul>
list-groups

You can add the “active” class to any item in the list to highlight it, also if you happen to place a badge inside it, it will be centered vertically and align it to the right, inside the item. Go ahead and try it.

Panels

Panels are a way to box in some content in your site or application, highlight it and give it a sense of unity. The panel markup is fairly simple, and its contents can be combined with different elements to achieve a unique look and feel.

Panels can have headers and footers and get a special meaning with the well known “sucess“, “error“, “warning“, etc. classes. For instance.

<div class="panel panel-success">
    <div class="panel-heading">Panel Heading</div>
    <div class="panel-body"><p>Some content here</p></div>
    <ul class="list-group">
        <li class="list-group-item">Lorem ipsum...</li>
        <li class="list-group-item">Dolor sit...</li>
    </ul>
</div>
panels

As you can see, panels work well with list groups, and also with non-bordered tables.


Customizer

Also new in this version is the Customizer in which, not only the look has changed, is far better organized and gives you control on things like the viewport width at which a certain Grid System takes control.

As always, you can set all your fonts styles and colors. It’s a huge topic on its own so I’d encourage you to go on your own and mess with it.

customizer

Browser Support

Long has been the suffering brought to all of us by Internet Explorer, it’s version six was a total nightmare and its predecessors still have a lot of catching up to do. In version 2.* Bootstrap’s team still supported the version seven of Microsoft’s browser. In this new iteration of the framework, support for IE seven is gone, as well as for Mozilla Firefox 3.6 and below.

Specifically, Bootstrap supports the latest version of all the major browsers (Safari, Opera, Chrome, Firefox and IE), in both Windows and Mac when there are both.

For IE, it supports version eight and forward, and although there are some properties that the browser doesn’t render, such as “border-radius“, the framework is fully functional only with some minor look and feel differences. Also IE eight requires respond.js for media query support.

To get a detailed list of workarounds and gotchas for the different browsers (cough Internet Explorer cough) look at the official docs.


Conclusion

Since its beginning, Bootstrap has been a great tool for rapid prototyping and creation of great sites and web applications and this third version is no different. If you need just one reason to use it, I would definitely go for the Grid System, with the growth of mobile browsing and the always increasing viewport sizes out there, responsiveness is a must now, more than ever. And in this latest version, that’s the area where Bootstrap shines the most.

August 09 2013

18:54

Real-World Off-Line Data Storage

In many projects there comes a time when you’ll need to store some data off-line. It may be a requirement or just an improvement for your users, but you have to decide which of the available storage options you will use in your application. This article will help you choose the best one, for your app.


Introduction

HTML5 introduced a few off-line storage options. AppCache, localStorage, sessionStorage and IndexedDB. Every one of them is suitable for a specific use. For example, AppCache can boost your application or let some parts of it work without an Internet connection. Below, I will describe all of these options and show a few code snippets with example usage.


AppCache

If a part of your application (or the whole app) can be used without access to the server, you can use AppCache to enable your users to do some things off-line. All you need to do is to create a manifest file where you would specify what should be cached and what shouldn’t be. You can also specify replacements for the files that require on-line access.

An AppCache manifest is just a text file with a .appcache (recommended) extension. It starts with CACHE MANIFEST and is divided in to three parts:

  • CACHE – files you specify here will be downloaded and cached the first time the user accesses your site
  • NETWORK – here you list the files that require an Internet connection to work properly, they will never be cached
  • FALLBACK – these files will be used when an on-line resource is accessed without a connection

Example

First, you have to define the manifest file on your page:

<!DOCTYPE html>
<html manifest="manifest.appcache">
...
</html>

You need to remember that the manifest file must be served with a text/cache-manifest MIME-type, otherwise it will not be parsed by the browser. Next, you need to create the file you defined earlier. For the purpose of this example, let’s imagine that you have an informational website with the ability to contact you and write comments. You can let users access the static parts of the site and replace the contact form and comments with other information so that the form and comments are inaccessible while off-line.

First, let’s define some static content:

CACHE MANIFEST

CACHE:
/about.html
/portfolio.html
/portfolio_gallery/image_1.jpg
/portfolio_gallery/image_2.jpg
/info.html
/style.css
/main.js
/jquery.min.js

Side Note: one bad thing about the manifest is that you can’t use a wildcard sign to indicate that, for example, a whole folder should be cached, you can only use a wildcard under the NETWORK section to indicate that all resources not listed in the manifest should not be cached.

You don’t need to cache the page on which the manifest is defined, it will be cached automatically. Now we will define fallbacks for the contact and comments sections:

FALLBACK:
/contact.html /offline.html
/comments.html /offline.html

Finally, we can use an * to stop all other resources from being cached:

NETWORK:
*

The final result should look like this:

CACHE MANIFEST

CACHE:
/about.html
/portfolio.html
/portfolio_gallery/image_1.jpg
/portfolio_gallery/image_2.jpg
/info.html
/style.css
/main.js
/jquery.min.js

FALLBACK:
/contact.html /offline.html
/comments.html /offline.html

NETWORK:
*

An important thing to remember is that your resources will only be cached once. They will not get cached when you update them, only when you change the manifest. A good practice is to enter in a comment with a version number and increase it every time you update the file:

CACHE MANIFEST

# version 1

CACHE:
...

LocalStorage & SessionStorage

These two storage options will be useful if you want to preserve something in your JavaScript code. The first one lets you save a value without an expiration date. This value will be accessible for any page with the same domain and protocol. For example, you may want to save the user’s application settings on his/her computer so he/she can adjust them to the computer they currently use. The second one will hold the values until the user closes the browser window (or tab). Also, the data is not shared between windows, even if the user opens a few pages of your application.

Something worth remembering is that you can store only basic types in localStorage/sessionStorage. So only strings and numbers will work. Everything else will be stored using it’s toString() method. If you need to save an object, you should do it using JSON.stringify (if this object is a class, you can just override the default toString() method to do it for you automatically).

Example

Let’s consider the previous example. In the comments and contact sections of the site, we can save what the user typed in, so if he/she accidentally closes the window, the values will still be there for him/her to continue later on. This will be a really simple piece of code using jQuery (since we will be using a field’s id to identify it later, each of the form fields will need to have an id attribute)

$('#comments-input, .contact-field').on('keyup', function () {
	// let's check if localStorage is supported
	if (window.localStorage) {
		localStorage.setItem($(this).attr('id'), $(this).val());
	}
});

When the comment/contact form is sent, we have to clear the value. Let’s do this by handling a submit event (here’s the most basic example):

$('#comments-form, #contact-form').on('submit', function () {
	// get all of the fields we saved
	$('#comments-input, .contact-field').each(function () {
		// get field's id and remove it from local storage
		localStorage.removeItem($(this).attr('id'));
	});
});

And finally, on page load, we will restore the values:

// get all of the fields we saved
$('#comments-input, .contact-field').each(function () {
	// get field's id and get it's value from local storage
	var val = localStorage.getItem($(this).attr('id'));
	// if the value exists, set it
	if (val) {
		$(this).val(val);
	}
});

IndexedDB

This is the most interesting storage option in my opinion. It allows you to store rather large amounts of indexed data into the user’s browser. This way, you can save complex objects, large documents, etc. and have your user access them without an Internet connection. This feature is useful for all kinds of applications – if you are making an email client, you can save the user’s emails so he/she can access them later, a photo album could save photos for off-line use, or GPS navigation can save a particular route and the list goes on.

IndexedDB is an object-oriented database. This means that there are no tables and no SQL. You store key-value pairs of data, where keys are strings, numbers, dates or arrays and values can be complex objects. The database itself is composed from stores. A store is similar to a table in a relational database. Each value must have it’s own key. A key can be generated automatically, you can specify it when you add the value, or it can be some field in the value (which can also be generated automatically). If you decide to use a field as a key, you will only be able to add JavaScript objects to the store (because simple numbers or strings can’t have any properties like objects can).

Example

For this example, let’s imagine that we have a music album. Now, I’m not going to cover building the entire music album app here. I will only be covering the IndexedDB part of the app, but the music album app itself is included with this article for you to download, so you can look at the complete source code there. First, we have to open the database and create the store:

// check if the indexedDB is supported
if (!window.indexedDB) {
	throw 'IndexedDB is not supported!'; // of course replace that with some user-friendly notification
}

// variable which will hold the database connection
var db;

// open the database
// first argument is database's name, second is it's version (I will talk about versions in a while)
var request = indexedDB.open('album', 1);

request.onerror = function (e) {
	console.log(e);
};

// this will fire when the version of the database changes
request.onupgradeneeded = function (e) {
	// e.target.result holds the connection to database
	db = e.target.result;
	
	// create a store to hold the data
	// first argument is the store's name, second is for options
	// here we specify the field that will serve as the key and also enable the automatic generation of keys with autoIncrement
	var objectStore = db.createObjectStore('cds', { keyPath: 'id', autoIncrement: true });
	
	// create an index to search cds by title
	// first argument is the index's name, second is the field in the value
	// in the last argument we specify other options, here we only state that the index is unique, because there can be only one album with specific title
	objectStore.createIndex('title', 'title', { unique: true });
	
	// create an index to search cds by band
	// this one is not unique, since one band can have several albums
	objectStore.createIndex('band', 'band', { unique: false });
};

The above code is pretty simple. You probably noticed the version and the onupgradeneeded event. This event is fired when the database is opened with a new version. Since the database didn’t exist yet, the event fires and we can create the store we need. Later we add two indexes, one to search by title and one to search by band. Now let’s see the process of adding and removing albums:

// adding
$('#add-album').on('click', function () {
	// create the transaction
	// first argument is a list of stores that will be used, second specifies the flag
	// since we want to add something we need write access, so we use readwrite flag
	var transaction = db.transaction([ 'cds' ], 'readwrite');
	transaction.onerror = function (e) {
		console.log(e);
	};
	var value = { ... }; // read from DOM
	// add the album to the store
	var request = transaction.objectStore('cds').add(value);
	request.onsuccess = function (e) {
		// add the album to the UI, e.target.result is a key of the item that was added
	};
});

// removing
$('.remove-album').on('click', function () {
	var transaction = db.transaction([ 'cds' ], 'readwrite');
	var request = transaction.objectStore('cds').delete(/* some id got from DOM, converted to integer */);
	request.onsuccess = function () {
		// remove the album from UI
	}
});

Pretty straightforward. You need to remember that all operations on the database are based on transactions to preserve consistency of data. Now the only thing left to do is to display the albums:

request.onsuccess = function (e) {
	if (!db) db = e.target.result;
	
	var transaction = db.transaction([ 'cds' ]); // no flag since we are only reading
	var store = transaction.objectStore('cds');
	// open a cursor, which will get all the items from database
	store.openCursor().onsuccess = function (e) {
		var cursor = e.target.result;
		if (cursor) {
			var value = cursor.value;
			$('#albums-list tbody').append('<tr><td>'+ value.title +'</td><td>'+ value.band +'</td><td>'+ value.genre +'</td><td>'+ value.year +'</td></tr>');

			// move to the next item in the cursor
			cursor.continue();
		}
	};
}

This is also not very complicated. As you can see, using IndexedDB you can store complex values really easily. You can also search for values by index, like this:

function getAlbumByBand(band) {
	var transaction = db.transaction([ 'cds' ]);
	var store = transaction.objectStore('cds');
	var index = store.index('band');
	// open a cursor to get only albums with specified band
	// notice the argument passed to openCursor()
	index.openCursor(IDBKeyRange.only(band)).onsuccess = function (e) {
		var cursor = e.target.result;
		if (cursor) {
			// render the album
			// move to the next item in the cursor
			cursor.continue();
		}
	});
}

You can use the cursor with the index just like how we did with the store. Since there may be a few entries with the same index value (if it’s not unique) we need to use IDBKeyRange. This will filter the results depending on what function you use. Here, we want to only get items by the provided band, so we used the only() method. You can also use lowerBound(), upperBound() and bound. The method names are pretty self explanatory.


Conclusion

So enabling off-line access for your users is not as complicated as it may seem. I hope that after reading this article you will make your applications more user-friendly by allowing them to access some parts (or maybe even all) of it without an Internet connection. You can download the sample app and experiment with it, adding more options or including some parts of it into your website.

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.
(PRO)
No Soup for you

Don't be the product, buy the product!

close
YES, I want to SOUP ●UP for ...