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

April 30 2012

01:06

How to Create a Simple Hover-Over Banner

Advertise here via BSA

Traditionally, to make a button or banner change when you hover over it, developers and designers have loaded two separate images — not the most efficient method. The most obvious drawback is that the image would be loaded only when the user hovers their mouse over the image and therefore they don’t experience a fluid, smooth hover effect, which is bad usability.

It also requires you to have two different files that need to be loaded, which means more files to manage, more HTTP requests to process, and more bloat on your site. This can quickly get out of hand if you have a lot of hover-over images on your site.

There must be a better way to approach this! Well, luckily there is a more efficient way, and that’s what we’ll learn in this tutorial.

Instead of having two separate images stored in two different files, you can combine both images within one image — a sprite — and place them next to each other on the canvas; this would mean that instead of loading the image dynamically, when the user hovers, both the static, first, image would be loaded as well as the hover, second, image. To do this we simply combine both the hover image and the normal image and then use some CSS to create a div (or class if you need a hyperlink, which we do in this tutorial), give the background image a width half the size of the actual image file, and then use CSS to make the background image shift to the left when the user hovers over it.

Part One: Preparing Your Image

Firstly, you need to prepare your image so that it will display correctly when you hover over it and shift the image to left — the key is to make the image completely symmetrical. For this tutorial, I will be using Apple’s “Available on the App Store” badge and having the image display the price when the user hovers over it.

1. Open your original, static image in Photoshop (you can follow along easily in Fireworks if you prefer).

2. Go to the menu and open Image – Canvas Size (or press Option + Command + C) and then double the width on your canvas — so in my case it would go from 200px to 400px. However, I prefer to add around 6 extra pixels (or any even number of pixels) as this allows space between both images and makes it look tidier. So, it would go from 200px to about 406px.

Screen Shot 2012-04-21 at 16.03.23

3. Select the layer that your image is placed on and then move it to the leftmost part of your canvas.

4. Duplicate the layer that contains your image and move the duplicated image to the rightmost part of your canvas and you should have two identical copies of your image side by side with the optional gap in the middle.

5. Now, you need to apply the style and changes to your secondary image that will display when the user hovers over it – so, for instance, double click the secondary image’s layer to bring up the Layer Style window.

6. You can add a color overlay to your image to give it a tint when the user hovers over it, so navigate to color overlay in the left sidebar of the window and check the box next to it.

Screen Shot 2012-04-21 at 16.09.42

7. Choose a color, in my case it’s black and give it a reasonable tint – I usually go for 80% opacity. This means that there’s enough tint to tell that it has changed but also allows the user to see the underlying image perfectly fine.

8. Once you’ve got a nice color going and applied the overlay, press Enter or OK.

9. Now, you have two images, one that will be displayed normally (the image on the left) and one that will be displayed when the user hovers over the original image (the one on the right). Now, you can add something to go on top of the hover image. Text is usually a good option.

10. Create a new layer above all the other layers and select the Text tool (or press T) and select an area above your hover image and start typing.

Screen Shot 2012-04-21 at 16.16.51

11. Now, add some additional formatting like a fancy font, change the size or maybe the color.

12. Save your image with an appropriate name (for this tutorial, it’s app-store-badge.png) in your desired location as a PNG file.

Part Two: Applying HTML and CSS

In this section, we add the actual HTML and CSS that will make the image work and move when the user’s mouse hovers over it.

1. Open up your text editor, for this tutorial I will be using Chocolat — my favorite text editor despite the fact it’s still in beta — and create a HTML and CSS file in the same directory (the same directory that contains your image).

2. In your HTML file, create the basic structure of a HTML document (the HTML5 structure is below):

<!DOCTYPE html>
<html lang="en-US">
<head>
<link rel="stylesheet" href="main.css" type="text/css" />
<title>CSS and HTML Hover Image</title>
</head>
<body>
<a class="hover-class" href="http://go.affogato.co/"> </a>
</body>

Screen Shot 2012-04-21 at 17.03.45

3. In this file, I’ve created an a tag in the body that will display the image as a link as well as perform just as if it were a div — it’s up to you as to whether or not you would like it to be a link or not and I’ve also linked the CSS file (main.css) within the head tag.

4. Now, if we switch from the HTML document to a CSS file, what we’re going to do is create the class and add the style to it. So, in your CSS file, add a new class as you can see, it is defined as .hover-class, and add the following code:

.hover-class {
height: 69px;
width: 200px;
display: block;
border: none;
background: url("app-store-badge.png") no-repeat;
}

5. Within the class, specify the height of the image and width of the first, original image because this is all we want to see at this moment – specify your image and ensure that there’s no border (to prevent Internet Explorer applying a border around the image) and that the display is set to block (this means there’s a small amount of white space above and below as well as preventing other HTML elements sitting next to it).

6. So, if you open up your HTML document, you’ll find that your original image is displayed however nothing happens when you hover over it — what’s up with that?

Screen Shot 2012-04-21 at 17.51.10

7. We need one final piece of CSS code to give the class something to do when a mouse is detected over it. We need to move the location of the background image to the right so the whole image shifts over and hence, displays the rest of your image. In your CSS file, add the following lines to make the background image shift revealing the hover image when it’s activated:

.hover-class:hover {
background-position: right;
}

8. Providing you’ve done everything correctly and aligned both images correctly, then when your mouse hovers over the image in your browser, it should change and move the position of the background image revealing what you wanted it to.

Recall when we placed both images within the Photoshop document and aligned them symmetrically? This is where many people go wrong — if both images are not symmetrical, they will appear to actually move to the left or right when you hover over them, which doesn’t look professional and is something you should look out for.

Essentially, the purpose of this is to make a website more efficient and user-friendly as the images are loaded beforehand with fewer HTTP requests, causing the effect to work more smoothly and the page to load faster.

WebKit1

Click here to download the source files.

April 13 2012

20:29

Nettuts+ Quiz #12: Quirky HTML Tags

Taking a break from the relatively technical focus of the past few quizzes, we’re going to do something very offbeat today. Yes, Offbeat with a capital O. Be it front end or back end programming, I’m sure you’re working with HTML tags every day. But as the saying goes, can you ‘catch ‘em all?’ Or rather, can you figure out what these rarely used HTML tags do?

I can already hear you chuckling with mirth, grasshopper. I’ve added a few deprecated tags just to keep you on your toes. Get everything right and prove that your HTML-fu is strong!




Sponsored post
soup-sponsored
20:53

March 31 2012

17:00

Answering a Designer’s Question: Should I Choose Web or Print?

Print and web are both huge areas of design and mean a lot in today’s world. Print has been with us for more than 100 years and we know pretty much everything about it, while web is a new area of design that became mainstream about 10 years ago. Before this, web design was totally unknown and only experts and developers knew its potential and helped it grow to how we know it today. Both areas of design have advanced so much in the past 10-15 years that they started to cross each others paths and while this can be beneficial, it can also create problems. We will talk about the advantages and disadvantages in this article and also about how the two areas of design differ from a designer’s perspective.

Main difference

The biggest and easiest difference to spot is the experience you get from them, which are quite different from each other. Reading a newspaper is totally different than browsing a website. Even reading a book is different than reading an ebook, although the process is the same.

While web design is usually made to be displayed on a screen, which can vary in size, print designs can be huge such as posters or ads. And while the user interacts with a website, it is impossible to interact with a newspaper or a poster. While web design creates an experience based on the user movements (clicks and scrolls) and can’t exist without user interaction, print design creates the experience through readers’ eyes moving around and searching for information.

Image by josephbradleycooper.

Canvas versus screen

Both mediums take into account the demographics of the audience, as they are very important while designing, creating, advertising and selling content. A detail worth mentioning is that designers use the same elements and concepts in both mediums: fonts and colors are the best example. While it is easier to play with them on a computer, therefore easier to use in web design, don’t forget that newspapers are also created on computers before being printed out. This means that pretty much everything you can do on a computer can also be done in a newspaper. Yes, to some extent.

  • Monitors come in different sizes, therefore designs have to look good on all of them, or at least on most of them.
  • Moreover, there are even more browsers and operating systems, all with their own rules which influence the way the code is interpreted.

While those issues exist and don’t seem like they’re about to disappear anytime soon, all web designers learn to work around them and just move on. Being able to provide cross-browser websites is actually an asset for a web designer today.

There are, indeed, some restrictions on the web due to technologies such as HTML5, CSS3 or JavaScript, but great design is created within restrictions given by a client or by the medium. And there are constraints in print as well, such as the size of any given newspaper, book or canvas. You can’t scroll on it. While the print uses a lot of paper for only a newspaper, the online magazines use bandwidth, a host and a domain which need to be renewed periodically. Both have advantages and disadvantages, but since the web went mainstream, less and less people became fond of print.

Regarding the things that need to be learned, both industries have their own standards. I would however say that it is much more demanding to be a web designer than a print designer. While typography, colors and concepts such as negative space are as important in web as in print, the second one doesn’t have technologies like HTML, CSS, PHP, ASP.Net and so on. Sure, there is some Quark, InDesign or Photoshop to learn, but the technical part is more demanding for web designers. This is probably the reason behind graphic designers who work on web not knowing how to code: it is not possible for everybody to know that much stuff without a hell of a lot of work. Being a complete designer is not an easy task.

When a print designer transitions to web he has some tough challenges to encounter.

  • The first one is, as said before, learning to code.
  • But wait, there are more. The canvas is fixed in print – each newspaper or publication has its own standards.
  • It is quite different from the web, where experts debate for a long time what should the right width of a website be?
  • Making things appear on a website like they did in Photoshop can also be a challenge.
  • Doing this in InDesign is easy – you just move elements around with mouse.
  • Web design doesn’t work the same way, so knowing code is crucial, as WYSIWYG editors usually add lots of junk and unnecessary code to your files.

Image by bcmng.

Moving the other way around might also be a challenge.

  • There are no pixels anymore; print designers work in inches or centimeters, depending on the region or country standards. A new concept is introduced to them as well: bleed and margins, things that do not exist in web. Printing is also a challenge of its own and a job that needs to be mastered.
  • Navigation is also a new concept for print designers, as flipping through a magazine doesn’t need such a concept. In web design it is totally different. Not having navigation is confusing and makes a website useless. And just having navigation is not enough. Designers need to make it stand out, while making sure the content is still more visible and important in hierarchy. The general web architecture is different than the one in print, therefore a print designer would need time to learn and adapt if switching careers from print to web.
  • Typography is also huge in both disciplines. However, in print it has always been important, but it has been ignored in web design until five years ago. When typographers had a boost of inspiration and showed the whole web industry how well used type can change a website, then many web designers started to experiment and play with fonts.
  • In print it is quite different. Once a publication sets some standard fonts, they are pretty much used all over the place and in each issue. Changing them doesn’t happen too often in print; it does, however, happen on the web. Since the introduction of Typekit, a web font service, and Google Fonts, the restriction to the fonts on the computers stopped.
  • Although not difficult to get used to, size is also different in web and print. While a type of 10 or 11 is suitable for print, the web demands larger sizes such as 12 or even 14. But with so many designers out there, there is not really a standardized font size for the web. If the font looks good, the size doesn’t matter. The style is also important, as in print serif fonts are suitable for blocks of text, while sans-serifs are suitable for text on web.
  • Images are an important part of design too. But there are some differences between how we handle images on the web and how we do it in print. The first difference is the color format. CMYK (for print) and RGB (for web)  are the standards. CMKY stands for Cyan, Magenta, Yellow and Key (which is usually black) while RGB stands for Red, Green and Blue, which every monitor, TV or digital equipment uses to create color.
  • Images need to be formatted and exported in CMYK if they will be printed out, otherwise the colors will not be shown exactly as on the computer screen. While this is not a difficult process, when moving from a domain to another it might take some time to get used to.
  • Image compression is also something worth mentioning. There is no need to have an image with more than 72dpi (doth per inch) on web, with level 8 or 9 (which equals “high”) JPEG files or PNG. In print it is good to have images of up to 300dpi in order for them to look good and have high-quality.

Image by birdfarm.

Another disadvantage of the print industry is the lack of interactivity. The content on web is not only readable, but also interactive, which makes the experience better. While newspapers do not have any interaction at all, this can also be their advantage. Interactive elements are often not usable in all browsers; there is no such problem in print, where things are kept simple.

If something is clearly similar between the two industries, then the grid system is it. Now I know not all web designers use it, but it is something which is becoming more and more popular on today’s web. While in web design it is still not a standard, a grid system is crucial in print.

Mastering both

People usually throw the same question out there: is it possible to master both print and web? Well yes, I think it is. If you understand that both industries have their own standards and are quite different, then mastering both of them is definitely possible. However, mastering only one of them might be enough for a career as well, so if you are interested in both of them, go for it. Otherwise it will not be a big issue. The fact that you don’t know how the print industry works will not be an issue if you deliver your work for the web in time and your employer is happy with you.

Bottom line

Designing for print and web are two different things, although they are bound by the same concepts. If your background lies in one of them, I am sure you will have no problem in switching to the other one if needed. You just have to keep in mind that while the print industry stalls (or at least drives forward very slowly), the web develops itself a lot year by year and this will only make the whole industry more challenging. Both domains have their own advantages and limitations and understanding them will only make you a better designer.

Until next time… how do you see the web and the print industry? Do you see yourself working in both at some point in time, or one of them is just not for you? Why do you think that?

February 13 2012

07:00

How To Build a Handwritten Letter Style Contact Form

Follow this step by step tutorial to create a traditional pen & paper inspired contact form in HTML and CSS. We’ll use a mix of basic and intermediate CSS techinques to give the form the appearance of a letter, then use the @font-face CSS property to transform the digital text into handwriting.

View the letter style contact form demo

The form we’re creating is styled with a lined background texture and a subtle shadow to give the impression of a paper sheet. The title and form fields will be styled as digital text, but instead of using rectangular form fields we’ll create dotted lines with a cursive font to give the appearance of a handwritten letter.

View the letter style contact form demo

The Photoshop concept

Before getting started with any coding I like to create a Photoshop concept to gain an initial idea of how the design will look. Start by giving the background a subtle Noise overlay with settings of 2% Uniform, Monochromatic.

Draw a white rectangle in the centre of the canvas then fill a 1px horizontal line with a light blue colour to replicate the pattern found on lined paper pads.

Hold ALT and hit the cursor keys to make a duplicate, then hold Shift and move the duplicated line 4 times (40px) to create a full page of lined paper.

Fill a black rectangle on a layer underneath the main page. This will be the base of our subtle page curl shadow.

Give the rectangle a Gaussian Blur, then press CMD+T to transform the shape. Right click and select Distort in order to hide the bottom corner behind the main page.

Reduce the opacity of the shadow to finish off the page curl effect.

Use typical font styling to create the printed portions of the letter. Make sure each text item is aligned to the baseline grid created by the lined pattern.

Switch over to Adobe Illustrator in order to create a dotted line effect. Illustrator’s Stroke tool makes it easy to create a series of circular dots by adjusting the Dash and Round cap settings.

Paste the lines back into the Photoshop document and align them according to the baseline grid.

The font styling within the form fields will be created with a handwritten font to give the appearance of a traditional pen & paper based letter. We’ll use Google Fonts to do this in CSS, so for now paste in some placeholder text.

Use a set of postage mark Photoshop brushes to style the send button to relate to the traditional handwritten letter theme.

Once the PSD concept is complete image graphics can be exported for use in the HTML/CSS version. Draw selections to create repeating swatches of the textured and patterned backgrounds.

Make sure an area of white space is included in the dotted image graphic in order to preserve the spacing and line height when the file is repeated.

Export any graphics that require a transparent background as PNG-24 images so they can be overlaid on the backgrounds without issue.

The HTML Structure

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Pen &amp; Paper Form</title>

<link href="style.css" rel="stylesheet" />

</head>
<body>

<div id="container">

</div>

</body>
</html>

Create a new HTML document and enter the basic structure of a HTML5 page, including the Doctype, page title, link to the CSS stylesheet and a simple container div to house our form.

<h1>Send a Letter</h1>

<form action="" method="post">
	<fieldset>
		<label for="name">Name:</label>
		<input type="text" id="name" name="name" />

		<label for="email">Email:</label>
		<input type="email" id="email" name="email" />

		<label for="message">Message:</label>
		<textarea id="message" name="message"></textarea>

		<input type="submit" id="send" value="Send" />

	</fieldset>
</form>

Type out the elements to create the overall form. The new HTML5 type="email" attribute can be used on the second form field, but otherwise the syntax is basic HTML. Make sure your labels correspond to the ID of each input for extra accessibility and usability points.

The CSS Styling

body, div, h1, form, fieldset, input, textarea {
	margin: 0; padding: 0; border: 0; outline: none;
}

body {
	background: #abb5cb url(blue-bg.png);
	font-family: Helvetica, Sans-Serif; color: #525c73;
	line-height: 40px; text-transform: uppercase;
}

#container {
	width: 560px; margin: 100px auto; padding: 51px 0 0 0;
	background: url(lines.png); position: relative;
}
	#container:before {
		content: ""; width: 19px; height: 365px; position: absolute; left: -19px; top: 0;
		background: url(shadow.png);
	}

The CSS file begins with a simple reset to remove any browser default styling, then the overall page styling can be added to the body. The #container div is transformed into the paper page with the help of the lined background image, then the shadow is added with the help of the :before selector. Absolute positioning is used to shift the shadow to the left of the main page so it aligns correctly.

h1 {
	font-size: 30px;
	text-align: center; letter-spacing: 5px;
	margin: 0 0 44px 0;
}

label {
	width: 150px; display: block;
	text-align: right; float: left;
	font-size: 18px; letter-spacing: 3px;
	margin: 0 10px 40px 0; clear: left;
}

Next up in the CSS is the styling of the printed or digital text. The Helvetica font family and colour is specified back in the body declarations, so all that’s left is to set the font sizing and to add some letter spacing to match the Photoshop concept. Adjust the margin under the header to keep everything aligned to the baseline and use a specific width on the labels so they all align flush to the right.

input {
	width: 300px; height: 40px; float: left; margin: -14px 0 0 0;
	background: url(dots.png);
	font-family: 'Shadows Into Light', cursive;
	font-size: 24px; color: #18326d; letter-spacing: 3px;
}

textarea {
	width: 300px; height: 200px; float: left; margin: -14px 0 40px 0;
	background: url(dots.png);
	font-family: 'Shadows Into Light', cursive;
	font-size: 24px; color: #18326d; letter-spacing: 3px;
}

The styling for the input fields begins as normal with a specific width and height, but instead of an outlined rectangle our fields are converted into dotted lines with the help of the dotted background image. The white space included in the image will allow the inputs and texarea elements to expand to any size. Grab the @font-face code from the Google Web Fonts page for Shadows Into Light and add it to the CSS to convert the input text into handwriting then adjust the margin to align the text above the dotted line.

input#send {
	width: 202px; height: 84px; float: right;
	margin: 0 70px 36px 0; padding: 0 0 0 77px;
	background: url(post-mark.png);
	font: bold 30px Helvetica, Sans-Serif; text-transform: uppercase; color: #525c73;
	cursor: pointer;
}

The final portion of CSS styles up the Send button. Currenly this input element is being styled by the generic input CSS declarations, so some properties need to be reverted. Otherwise the main graphic is added as a background image and the whole element is moved into place with margins.

UPDATE! Auto-Expanding Textarea

James Seymour-Lock made a great suggestion on Twitter that the textarea should expand as the user types in order to hide the ugly scroll bar. Why didn’t I think of that?!

$(document).ready(function() {
	$('textarea#message').autoResize();
});

This cool functionality can be easily added with the help of a ready made jQuery plugin. jQuery.fn.autoResize provides the exact effect we need. Add the script files to the head of the HTML file and activate the jQuery plugin.

The Final HTML/CSS Form

View the letter style contact form demo

This leaves the styling of our handwritten letter inspired form complete. The lined background image and page curl shadow give the appearance of an actual sheet of paper, whereas the dotted lines and handwriting font styling replicate how printed forms are filled out in real life.

View the letter style contact form demo

November 21 2011

07:00

October 31 2011

07:00

Create a Typography Based Blog Layout in HTML5

Last week I posted part one of this tutorial series covering the process of creating a typography based blog design in HTML5 and CSS3. We finished off the Photoshop concept with the design based on a strict grid and text laid out in our desired typeface. Now let’s replicate the design in a static HTML5 and CSS3 prototype before finishing it all off as a fully working WordPress theme.

View the Typo blog design Photoshop tutorial

Head back to last week’s tutorial post if you want to follow the step by step process of building this design in Photoshop. The WordPress theme we’re creating is called Typo. It’s a design that’s entirely based on typography to allow the content to shine. To allow the design to work without the use of any graphical interface elements it is based on a strict grid to balance the design and tie everything together.

View the Typo blog design Photoshop tutorial

Preparing the concept

With this design being pretty minimal and largely typography based there’s not much in the way of background image files that need exporting. The only files we’ll need to save are the background texture file and a couple of icons. However, to make life easier while coding up the design we can also export copies of the columns and grid lines so we can quickly align our elements.

This particular layout will be built with HTML5 elements, so it’s important to take a moment to familiarise yourself with the elements and check whether they fit into the layout semantically.

The HTML5 Structure

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Typo</title>

<link href="style.css" rel="stylesheet" />

<link href='http://fonts.googleapis.com/css?family=Droid+Serif:400,400italic' rel='stylesheet' type='text/css'>

<script src="js/scripts.js"></script>
</head>

<body>
<div id="container">

The static HTML file begins with a HTML5 Doctype and the usual content for the <head> section of the document, including the page title and link to the CSS stylesheet. Our design is using a somewhat unusual font courtesy of Google’s Web Fonts library, so the relevant code is also added. It’s important not to just straight swap your <div> tags for <section> tags when coding in HTML5, sometimes a <div> is still the most semantic choice, like when adding a wrapper or container div to your code.

<header>
	<h1><a href="#" title="Return to the homepage">Typo</a></h1>

	<nav>
		<ul>
			<li><a href="#">Home</a></li>
			<li><a href="#">About</a></li>
			<li><a href="#">Archives</a></li>
			<li><a href="#">Contact</a></li>
		</ul>
	</nav>
</header>

One new HTML5 element we can make use of in place on a standard div is the <header> element, which can also contain a <nav> element to wrap our main navigation menu. The h1 is marked up as the blog title, with a handy anchor title describing where the link goes. If you remember in our concept we numbered the menu items, an obvious option would be to use an <ol> element, but semantically this isn’t correct because there’s no consecutive relationship between our menu links, the number is just for visual flair so we’ll add them later with CSS.

<div id="content" role="main">
	<article>
		<h2><a href="#">Getting your stock photos seen</a></h2>

		<p>Lorem ipsum dolor sit amet[...]leo placerat.</p>

		<ul class="postinfo">
			<li>17th October 2011</li>
			<li>Posted in <a href="#">Articles</a></li>
			<li><a href="#">Continue Reading &raquo;</a></li>
		</ul>
	</article>

I originally used a <section> element to contain my page content, but after some reading it turned out this wasn’t 100% semantic. The preferred method would be to use a plain old <div>, but the addition of the ARIA role attribute of ‘content’ gives a little extra meaning to the tag. Inside the content area each blog post can be contained in its own <article> tags with the usual HTML elements mocking up the dummy content.

	<nav id="pagination">
		<ul>
			<li class="older"><a href="#">&laquo; Older posts</a></li>
			<li class="newer"><a href="#">Newer posts &raquo;</a></li>
		</ul>
	</nav>

</div>

Underneath the series of blog posts is a couple of pagination links. Usually pagination links wouldn’t qualify as being important enough for the <nav> element (which can be used in multiple places, not just for the main menu), but for a blog layout I see pagination links as one of the primary navigation elements to access further content.

<aside id="sidebar">
	<section id="about">
		<h3>About me</h3>
		<p>Typo is a WordPress theme based entirely on a balanced typographic design. A strict grid layout keeps everything tidy, allowing the content to shine. <a href="#" class="more">Find out more &raquo;</a></p>
	</section>

	<section id="categories">
		<h3>Categories</h3>
		<ul>
			<li><a href="#">Articles</a></li>
			<li><a href="#">Design</a></li>
			<li><a href="#">Graphics</a></li>
			<li><a href="#">Inspiration</a></li>
			<li><a href="#">Retro</a></li>
		</ul>
	</section>

Until the <aside> spec was revised it didn’t have a semantic use as a sidebar, but it can now be safely used without the semantic police knocking at your door. The sidebar in this design contains a number of various sections, which lend themselves well to being marked up with <section> tags over plain old divs.

	<section id="search">
		<h3>Search</h3>

		<form method="get" action="#">
			<fieldset>
				<input type="text" id="searchbar" placeholder="I'm looking for&hellip;" />
				<input type="submit" id="searchsubmit" value="Search" />
			</fieldset>
		</form>

	</section>

</aside>

At the bottom of the sidebar is a simple search bar, which allows us to touch on some of the handy new form related features in HTML5. The one feature we can make use of is the placeholder attribute, which allows us to enter a passage of text to create the popular in-field label effect.

</div>

<div id="footer-container">
	<footer>
		<ul id="credits">
			<li class="wordpress"><a href="http://wordpress.org">Powered by WordPress</a></li>
			<li class="spoongraphics"><a href="http://www.blog.spoongraphics.co.uk">Theme by SpoonGraphics</a></li>
		</ul>

		<p id="back-top"><a href="#">Back to top</a></p>
	</footer>
</div>

The layout is then finished off with the footer area, which in the case of this design needs to be outside of the main container area to allow it to span across the whole page. The footer area itself fits well as a <footer> element and contains a couple of handy links.

The full HTML layout

View the full annotated HTML5 code

View the full annotated HTML5 code

The CSS Styling

With the HTML structure in place the document can now be styled to match the Photoshop design concept.

body, div, h1, h2, h3, h4, h5, h6, p, ul, ol, li, dl, dt, dd, img, form, fieldset, input, textarea, blockquote {
	margin: 0; padding: 0; border: 0;
}

body {
	background: #dedede url(images/bg.jpg);
	font-family: 'Droid Serif', serif; font-size: 14px;
	line-height: 24px;
	color: #666;
}

a {
	color: #4b7ea9; font-style: italic;
}
	a:hover {
		color: #105896;
	}

header a, h2 a {
	color: #666; font-style: normal; text-decoration: none;
}

#container {
	width: 916px; margin: 0 auto; padding: 48px 22px 0 22px;

	background: url(images/grid.jpg); overflow: hidden;
}

The CSS file begins with a simple reset, then the global styling is added to the body. The Google Web Fonts code has already been added to the HTML, so our desired font can be called directly in the CSS. The subtle texture background is added and the body text styling set to 14px #666 with a 24px line-height to match the baseline grid. Global link styling is set up, but is removed from links in the header and blog post H2 titles to match the concept. The container div is then centred up and a temporary grid image added as a background to make it easy to line up page elements according to the original grid based design.

header {
	margin: 0 0 98px 0;
}

	header h1 {
		float: left; font-size: 36px;
		font-weight: normal;
	}

	header nav {
		float: right; text-align: right;
		padding: 6px 0 0 0;
	}
		header nav ul {
			list-style: none;
		}
			header nav li {
				float: left; font-size: 18px;
				width: 136px; margin: 0 0 0 20px;
			}

			header nav li:nth-child(1):before {
				content: "1. ";
				color: #a2a2a2;
			}
			header nav li:nth-child(2):before {
				content: "2. ";
				color: #a2a2a2;
			}
			header nav li:nth-child(3):before {
				content: "3. ";
				color: #a2a2a2;
			}
			header nav li:nth-child(4):before {
				content: "4. ";
				color: #a2a2a2;
			}
			header nav li:nth-child(5):before {
				content: "5. ";
				color: #a2a2a2;
			}

Margins and padding are used to line up the elements according to the grid lines, with random figures like 98px being needed to ensure everything lines up correctly. Making live adjustments with the help of plugins such as Firebug is much easier than confusing your brain with complex calculations. Earlier we talked about those visual numbers next to the menu items. They aren’t anything important so they can be added using CSS so they don’t actually appear in the HTML markup, this is done using :nth-child and :before selectors to add the numbers using the content property.

#content {
	float: left; width: 526px;
	margin: 0 98px 0 0;
}

	#content article {
		margin: 0 0 67px 0;
	}
		#content article h2 {
			font-size: 30px; margin: 0 0 29px 0;
			font-weight: normal;
		}

		#content p {
			margin: 0 0 24px 0;
		}

		#content .postinfo {
			list-style: none; overflow: hidden;
		}
			#content .postinfo li {
				float: left; width: 136px; margin: 0 20px 0 0;
				font-style: italic; color: #a2a2a2;
			}

#pagination {
	overflow: hidden; margin: 0 0 120px 0;
}
	#pagination ul {
		list-style: none;
	}
		#pagination li {
			font-size: 18px;
		}
			#pagination li.older {
				float: left;
			}
			#pagination li.newer {
				float: right;
			}

The CSS to style up the dummy blog posts is then added, starting with the content div. A width is calculated according to the columns and gutters, which when combined with the width of the sidebar and any margins equals the width of the container div. The font styling of the H2 elements is added and margins used to keep everything tight to the baseline grid.

#sidebar {
	width: 292px; float: left;
	padding: 4px 0 0 0;
}
	#sidebar h3 {
		font-size: 18px; font-weight: normal;
		margin: 0 0 25px 0;
	}		

	#sidebar ul {
		list-style: none;
	}

	#sidebar section {
		margin: 0 0 47px 0;
	}

	#sidebar #about a.more {
		display: block; text-align: right;
	}

	#sidebar #categories {
		width: 136px; float: left;
		margin: 0 20px 0 0;
	}

	#sidebar #social {
		width: 136px; float: left;
	}

The sidebar element is then floated alongside the main content div and any content not already styled is given treatment to match the Photoshop concept. Some sidebar elements such as the categories and social links and placed side by side, so specific widths are added according to the grid.

#sidebar #search #searchbar {
	width: 230px; height: 36px; float: left;
	border: 1px solid #c7c7c7; padding: 0 45px 0 15px; margin: -8px 0 0 0;
	background: #e2e2e2; /* Old browsers */
	background: -moz-linear-gradient(top, #e2e2e2 0%, #ffffff 16%); /* FF3.6+ */
	background: -webkit-linear-gradient(top, #e2e2e2 0%,#ffffff 16%); /* Chrome10+,Safari5.1+ */

	font-size: 14px; font-style: italic; color: #a2a2a2;
}
	#sidebar #search #searchsubmit {
		width: 17px; height: 17px; float: right; margin: -27px 15px 0 0;
		background: url(images/search-icon.png); text-indent: -9999px;
	}

The search bar in the concept is the only element with visual styling other than typographic tweaks. The gradient effect added to the sidebar can be easily replicated with CSS gradients, whereas the small icon image can be quickly added with good old image replacement techniques.

#footer-container {
	background: rgba(0,0,0,0.2);
	overflow: hidden;
}
	footer {
		width: 916px; margin: 0 auto; padding: 10px 22px 50px 22px;
	}
	footer #credits {
		list-style: none; float: left;
		}
		footer #credits li {
			float: left; margin: 0 6px 0 0;
		}
			footer #credits li.wordpress a {
				display: block; width: 20px; height: 20px;
				background: url(images/credits.png) no-repeat 0 0; text-indent: -9999px;
			}
			footer #credits li.spoongraphics a {
				display: block; width: 25px; height: 20px;
				background: url(images/credits.png) no-repeat -30px 0; text-indent: -9999px;
			}

		footer #back-top {
			float: right; font-size: 12px;
		}

The footer area of the design is filled with a darker texture, which can be replicated with CSS using the RGBa color mode with a 20% alpha opacity on a black fill. The footer-container div will span the full page, so the footer div requires new widths and margins to match the main content container area. Finally the footer credits are added using image replacement techniques and the back to top link is moved into place with a right float.

The full CSS stylesheet

View the full annotated CSS stylesheet

View the full annotated CSS stylesheet

The Final HTML5/CSS3 Prototype

View the HTML5/CSS3 prototype

The final working prototype is now ready for testing before the design is converted into a full WordPress theme. Everything appears to be working as it should in Firefox, Safari and Chrome, and unbelievably IE9 has no problem rendering those HTML5 elements too. Some additional work is required for Internet Explorers 7 and 8, but I’ll save those for a rainy day.

View the HTML5/CSS3 prototype

October 03 2011

16:09

Designers Know Your Code: Web Design Tutorials


  

As almost any web designer worth their salt, and a large percentage of web developers will tell you, to be fully considered a web designer you have to have some background in code. Not to the depth that full on developers must, but it really is unfair to the rest of those working on a website with us if we do not have some knowledge in a handful of key areas. Which is where these web design tutorials come in.

In this post we have gathered a handful of useful tutorials from these various areas of code that designers should have their hands in. We have standard CSS and CSS3 tutorials, HTML5 and also Javascript tuts as well. A little something for all three of the main code branches that web designers need to always be improving their grasps on. We hope that you find these web design tutorials helpful in your next or current project!

CSS Tutorials

30 CSS Best Practices for Beginners – CSS is a language that is used by nearly every developer at some point. While it’s a language that we sometimes take for granted, it is powerful and has many nuances that can help (or hurt) our designs. Here are thirty of the best CSS practices that will keep you writing solid CSS and avoiding some costly mistakes.

6 Ways To Improve Your Web Typography – Typography on the web is anything but simple, and for many, it is a troubling mystery. Today, we’re going to review six ways that web designers and developers can improve the typography of the sites they create.

3 Easy and Fast CSS Techniques for Faux Image Cropping – This article is a summary of a 3 fast and easy CSS techniques you can use to display only a portion of an image in your content. All techniques explained here actually need only couple of lines of CSS.

Build Multi-level Multi-column Multi Menus with pure CSS – works perfectly in most browsers, including IE 6, using absolutely no javascript

CSS Absolute Positioning: Create A Fancy Link Block – some tricks to create a fancy link block that make our links more attractive.

How to Create a Beautiful Dropdown Blogroll Without JavaScript – Dropdown menus are a great way of including a long list of links without cluttering up your page. The issue though is that they can be hard to style, but look quite ugly if you don’t. There isn’t a lot of flexibility with HTML’s select tags.

CSS3 Tutorials

CSS3 Minimalistic Navigation Menu – a simple CSS3 animated navigation menu, which degrades gracefully in older browsers and is future-proofed to work with the next generation of browsers.

CSS3 Tutorial: Sleek Card Pockets using CSS Only – learn how to create web card pockets using some great new CSS3 techniques.

CSS3 Animated Vignette Buttons – This tutorial uses a patterned background and places vignette-style .pngs over the top which are animated using transition.

CSS3 Music Player Menu – This tutorial maximizes power of CSS3 to create a CSS Music Player Menu with a Photoshop-like effect.

3D Animation Using Pure CSS3 – This tutorial uses the perspective property to create the 3d effect and transform and transition, to animate it.

Create a Swish CSS3 Folded Ribbon in 5 Minutes – Take one line of markup, a couple of CSS3 rules (no images), and you can have yourself a swish folded ribbon effect in five minutes.

HTML5 Tutorials

HTML5 : The Basics – This tutorial introduces HTML5 and its basic features as well as explains the key differences from HTML 4.01 and XHTML 1.0 so you can start preparing yourself and your sites for the transition.

Have A Field Day With HTML5 Forms – Take a look at how to style a beautiful HTML5 form using some advanced CSS and latest CSS3 techniques.

Preparing for HTML5 with Semantic Class Names – A brief introduction to the new structural elements in the HTML 5 Working Draft, and how to use semantic class names in HTML 4.01 or XHTML 1.0 markup that correspond to the names of those structural elements.

Drag and Drop – This tutorial will teach you how to create a HTML 5 page that uses the new drag and drop feature.

How to Make an HTML5 iPhone App – This tutorial will show you how to create an offline HTML5 iPhone application, specifically, a tetris game.

Create Vector Masks Using the HTML5 Canvas – This tutorial looks at how to use the canvas tag and clipping to create images that aren’t so rectangular.

Javascript Tutorials

Javascript – An easy introduction – Javascript is used to add interactivity and functionality to a site. It has many uses, from detecting the viewers web browser to validating form input.

Nested Arrays in Javascript – Like most programming languages, JavaScript lets you create arrays inside arrays, known as nested arrays. In a nested array, the elements of one array are themselves arrays.

jQuery for Absolute Beginners – Fifteen video tutorials that teach you EXACTLY how to use the jQuery library. Start by downloading the library and eventually work up to creating an AJAX style-switcher.

iPhoto-like image resizing using Javascript – This tutorial uses the script.aculo.us slider control to capture input values, then converts those values into something useful.

Learn How To Detect Browser in Javascript – In this tutorial you will learn how to detect the browser in javascript so that you can then serve the suitable information.

Words Validation with Javascript – This tutorial will explain you how to filter out inappropriate words from being updated or sent from your website.

(rb)

07:00

September 29 2011

19:34

What Is HTML? The Anatomy of an HTML5 Document

screenshot

This is the second article in our series on the absolute fundamentals of web development. Our first article explained in detail what HTML is on a conceptual level. We looked at what a markup language is, what tags are and how HTML compares to other important pieces of the web development puzzle such as CSS.

Join us today as we move on and take a look at each basic piece of an HTML document. I’ll explain all that stuff at the top of an HTML file that confuses you and outline the basic structure that you’ll follow for creating your own HTML files.


Like the article? Be sure to subscribe to our RSS feed and follow us on Twitter to stay up on recent content.

DOCTYPE

The very first thing that you typically see in an HTML file is the DOCTYPE declaration. Before HTML5, this could be a very confusing bit of code that looked something like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

</ br>

There’s a lot going on here and every bit of it speaks to either the web browser, the reader or both. The “PUBLIC” part just speaks to the availability, the DTD stands for Document Type Definition, which declares the version of HTML being used and the final section is a URL pointing to where the DTD can be found.

The words “loose,” (or transitional) “strict” and “frameset” refer to different versions of HTML 4, which allowed for slightly different markup. These were essentially just to help transition developers from older versions of HTML.

The HTML5 DOCTYPE

There are several DOCTYPEs to choose from, which can be monumentally confusing for new developers. Fortunately, HTML5 completely simplifies the situation with a refreshingly simple DOCTYPE:

<!DOCTYPE HTML>

</ br>

See how easy that is by comparison? It really is a beautiful thing.

What Does the DOCTYPE Do?

Now we’ve seen what a DOCTYPE looks like but we haven’t really discussed what it does. The answer is that the DOCTYPE tells the browser which type of HTML to expect, which in turn affects how the browser renders the page.

As you explore web development more, you’ll learn that there’s a huge emphasis on “standards-based development.” The general idea is that if we all follow certain rules and standards, web development will be a more cohesive and consistent practice. This is better for developers, better for browsers and most importantly, better for users.

DOCTYPEs were originally designed to trigger “standards mode” in browsers, which meant that the page was rendered using newer web standards. Similarly, older pages without a DOCTYPE triggered “quirks mode” in browsers, which allowed for older practices to be used that wouldn’t function properly in standards mode.

The new, very simple HTML5 DOCTYPE is supported in all major browsers, and it triggers standards mode in all of them. The DOCTYPE also helps you validate your code, which ensures that current standards are being adhered to. Every page that you create should use a DOCTYPE and hopefully be fully standards compliant.

Root Element

After the DOCTYPE, the HTML really begins. This is indicated by the HTML Root Element. If your entire HTML is a tree, this is the root from which everything else sprouts.

The Root Element is defined by a “tag,” which we learned about in our last article. In this case, it’s the “HTML” tag.

<!DOCTYPE HTML>
<html lang="en" xml:lang="en">
  <!-- Everything Goes Here -->
</html>

</ br>

Notice that the root element includes a language attribute, in our case English. Always be sure to indicate the appropriate language for every page you create.

Everything else that we will add to this page is situated inside of the Root Element. It is the container for every scrap of information and piece of content, the only exclusion being the DOCTYPE.

Head Element

The next thing you’ll encounter in an HTML document is the “head” section. The head tag is exactly what you’d expect it to be:

<head>
  <!-- Some Code Goes Here -->
</head>

</ br>

The stuff that goes into the head section is primarily informational, it tells both you and the browser certain things about the page such as the title, the charset, etc. This is also where you traditionally load in important external resources.

There are a few important things that go into a head tag. Let’s look at them one by one.

Meta Tags

As you can probably guess, meta tags hold metadata about the page. Metadata takes many forms and can include keywords, authors, descriptions, etc. Here are a few notable inclusions:

Charset
This is pretty boring stuff, the charset is typically set to UTF-8 and essentially tells the browser which character encoding to use.

Your pages should definitely include an indication of which charset to use. Don’t over think it, it’s just one of those things you need to stick in your template. Below is a typical charset declaration in HTML5.

<meta charset="utf-8">

</ br>

This is yet another thing that has gotten easier with HTML5. Check out the version of this snippet required for HTML 4.01:

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

</ br>

Some other typical metatags include description and author. Here’s a quick, self-explanatory example of each of these:

Description

<meta name="description" content="Some description about your page">

</ br>

Author

<meta name="author" content="Josh Johnson">

</ br>

Title

Another thing that goes inside the head portion of your document is the title tag. This is a very simple piece of code that simply states whatever you’d like the title of the page to be. Here’s an example:

<title>Design Gallery, Deals, Tutorials &amp; Community | Design Shack</title>

</ br>

This title is usually shown to the user at the very top center of the browser window, on a tab, etc.

screenshot

Links and Scripts

The last thing we’ll discuss regarding the head tag is the inclusion of external resources. In a very simple web page, you’ll typically see these take the form of a stylesheet or script:

<link rel="stylesheet" href="style.css">
<script src="js/jquery.js"></script>

</ br>

Here I’m essentially loading my CSS file as well as jQuery (a JavaScript library) into the page. If these resources are included in the source files but not linked to in the head section, they will not function. Note that the links for these could either point to something in the local folder hierarchy (as above) or something hosted on another web server.

The link used above for the CSS file uses a link relation (rel=”stylesheet”). For more on link relations, check out this article.

Also, as an alternative to linking to external files, you can embed code right into the head element. Here’s an example with CSS, but the same can be done via the “script” tag and JavaScript (embedded scripts are often placed at the end of the body element instead).

<style type="text/css">
	a { text-decoration: none; }
	p { color: #333; }
</style>

</ br>

Body Element

The final portion of an HTML page is the most important. Everything inside of the body element defines the content and structure of your page. As far as development time, you’ll likely use a set template for everything above and spend a few minutes customizing it for specific projects. The rest of your HTML time will be spend inside the body element.

<body>
  <!-- Page Content Goes Here -->
</body>

</ br>

Putting it All Together

Now that we’ve walked through each individual piece of an HTML file, let’s put it all together into one extremely basic HTML5 template.

<!DOCTYPE HTML>
<html lang="en" xml:lang="en">
 
<head>
	<meta charset="utf-8">
	<title>Design Shack</title>
	<meta name="description" content="A Very Basic HTML5 Anatomy">
 
	<link rel="stylesheet" href="style.css">
	<script src="js/jquery.js"></script>
</head>
 
<body>
  <!-- Page Content Goes Here -->
</body>
</html>

</ br>

An Overview

A thousand apologies for the mundane nature of this topic, beginners are often turned off by boredom at this point but hang in there, the real fun of HTML is everything between the body tags, which we haven’t even discussed!

All of these pieces were necessary to accurately paint the picture of what an HTML document actually is. We now see that an HTML document has a DOCTYPE that tells the browser how to render the page and helps ensure the proper standards are being used.

We also know that there’s a set hierarchy to how HTML pages are structured. Just about everything but the DOCTYPE is thrown into the root element, meaning it is the “parent element” of the head and body elements, which in turn have their own children.

screenshot

The basic structure of an HTML document is referred to as the DOM, or the Document Object Model. This is almost always metaphorically referred to as a tree and depicted like image above. Our own Jack Rocheleau wrote an in-depth look into the DOM titled Deeper Study Into the WWW’s Document Object Model. For the next set in understanding the basic structure of an HTML page, check out that article.

Conclusion

This article represents a very brief overview of how an HTML skeleton is structured and the types of things that are typically included. It is by no means exhaustive, but should serve as a good basic introduction to these topics.

When you’re just starting out in code, most people will simply give you a template for all of the code above without really explaining what it all does. This can leave a sizable hole in your education so it’s important to read through this information and attempt to understand what you can.

Stay with us in this series and check back soon as we answer another important question: What is CSS?

Tags: HTML

September 26 2011

07:00

You’re Doing it Wrong: Common HTML Tag Misuses

View the source code of a hand full of websites featured in CSS galleries today and you’ll often see the same errors appear time and time again. These mistakes are usually habits we picked up during our early days of coding that have stuck around due to lack of clarification. This post rounds up a collection of common HTML tag and element misuses and describes the best practice to correctly and semantically use them in your markup.

Misuse of the <br> tag

The <br> HTML tag

How not to use the <br> tag

A common misuse of the <br> tag is to use it to create spaces or gaps in your content. WYSIWYG editors are notorious for injecting multiple line breaks or empty paragraph tags.

How to properly use the <br> tag

The <br> is used to insert a line break in a sentence. Examples might be to correctly lay out an address. Use paragraph elements to split up your content and use CSS margins to alter the spacing between them.

Misuse of the <div> tag

The <div> HTML tag

How not to use the <div> tag

When we first get to grips with HTML and coding in CSS we often get carried away with our divs and surround almost every page item with its own div tags.

How to properly use the <div> tag

The <div> tag is perfectly acceptable to use to define the main page structure, but always try to use more suitable tags for your page elements. Paragraph tags, ordered/unordered lists and definition lists can be more semantic choices.

Misuse of the <small> tag

The <small> HTML tag

How not to use the <small> tag

The <small> tag is often wrongly used as its name suggests, to create text that’s small in size.

How to properly use the <small> tag

CSS should always be used for presentational styling, so use the font-size CSS property to control your text sizes. The <small> HTML tag is reserved for defining “smallprint” or legal text.

Misuse of the <hr> tag

The <hr> HTML tag

How not to use the <hr> tag

The use of the <hr> is pretty rare these days, but when you do see it you can guarantee it’s being misused as a presentational line between sections of a page.

How to properly use the <hr> tag

These days the CSS border property is the correct solution in most situations, however the <hr> tags still has its use in specific situations when defining layouts containing copy such as book chapters or poetry stanzas.

Misuse of the <title> tag

The <title> HTML tag

How not to use the <title> tag

In most cases the HTML <title> tag (not the attribute) is misused in two extremes. It either contains no valuable information, or it’s packed full of endless keywords for “SEO”.

How to properly use the <title> tag

The <title> should accurately but concisely describe the contents of the page. It’s important to include keywords that relate to the content as it is recognised by search engines, but it shouldn’t be abused.

Misuse of the <img> tag

The <img> HTML tag

How not to use the <img> tag

The misuse of the <img> is actually more to do with the misuse of its alt attribute. Often the text within the alt attribute is completely irrelevant (if it exists at all!).

How to properly use the <img> tag

<img> tag alt attributes should contain an accurate description of the image. If the image is being used as a link give an insight to where the link will go. If the image has no importance an empty alt attribute is acceptable.

Misuse of the <label> tag

The <label> HTML tag

How not to use the <label> tag

<label> is another tag that is often left out altogether rather than being misused. When it does appear it rarely includes the for attribute.

How to properly use the <label> tag

Use the <label> tag to relate a field to its descriptive label. For extra usability points add the for attribute to allow the user to click the label to activate the relevant input field.

Misuse of the <address> tag

The <address> HTML tag

How not to use the <address> tag

The name of the <address> wrongly suggests that it should be used to surround a postal address on a contact page.

How to properly use the <address> tag

The correct use of the <address> tag is to define the author or owner of the document. Therefore it’s usually wrapped around their name along with their contact email address or telephone number.

August 29 2011

07:00

How To Code a Blog Theme Concept in HTML & CSS

Last week we went through the process of creating a clean blog theme layout in Photoshop. Now, let’s transform the visual concept into a working HTML/CSS prototype web page before finishing everything up as a complete theme next week. We’ll build the page structure with clean HTML, then style up as much as possible using CSS styling to create a lean website design that still replicates the original concept.

View the HTML and CSS website prototype

If you missed last week’s tutorial, we created the homepage concept for a WordPress theme called Ticket Stub. It’s based on the idea of movie review, but the clean layout and basic styling keeps it generic enough to be used for any topic.

View the Photoshop design tutorial

We can recreate the majority of the design using pure CSS styling, but we’ll still need to export a couple of image files. Toggle off all other layers in order to save out a copy of elements such as the logo.

The final list of images is made up of mostly icon png files. The two post thumbnails will be used temporarily to mock up a sample post.

The HTML Structure

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Ticket Stub</title>

<link href="style.css" rel="stylesheet" />

</head>

<body>

<div id="container">

</div>

</body>
</html>

Our static HTML file begins with a typical document structure consisting of doctype , link to the CSS stylesheet and a container div to wrap our page elements.

<div id="header">
	<h1><a href="#"><img src="images/logo.png" alt="Return to the homepage" id="logo" /></a></h1>

	<ul id="subscribe">
		<li class="rss"><a href="#">Subscribe by RSS</a></li>
		<li class="twitter"><a href="#">Follow on Twitter</a></li>
	</ul>
</div>

The first portion of content in the design is the header. We don’t have any kind of title or introduction in this design which would fit into a <h1> tag, so we’ll use it for the logo. The two subscribe options can be written as a <ul>, with classes on the <li> elements to allow for unique styling with the icon images.

<div id="main">
	<div id="content">
		<!--Main column-->
	</div>

	<div id="side">
		<!--Sidebar-->
	</div>
</div>

The main content area of the design is split into two columns. A wide column for the main post content and a smaller sidebar. These two divs are marked up inside the “main” div to allow for the child floats to be easily cleared.

<div class="post">
	<h2><a href="#">Captain America Kicks Ass!</a></h2>

	<a href="#" class="post-thumbnail"><img src="images/temp-post-thumbnail1.png" alt="Read the full post" /></a>

	<p>Lorizzle ipsum dolor sizzle ghetto, consectetuer fizzle elit. Sheezy doggy velizzle, i saw beyonces tizzles and my pizzle went crizzle volutpizzle, suscipit cool, own yo' vizzle, arcu. Pellentesque eget phat. My shizz erizzle. For sure izzle dolizzle for sure turpis tempizzle sizzle. Maurizzle i saw beyonces tizzles and my pizzle went crizzle nibh et turpizzle. Bizzle izzle i saw beyonces tizzles and my pizzle went crizzle. Pellentesque eleifend pot nisi. In hac habitasse platea dictumst. Pimpin' dapibizzle. Cool tellus owned, pretizzle eu, mattis uhuh ... yih!, eleifend dang, nunc. Ma nizzle suscipizzle. Integizzle shizzlin dizzle away sizzle purus. Mammasay mammasa mamma oo sa at dope. Yo mamma erizzle. condimentizzle, turpizzle nizzle congue consectetuer, brizzle libero bling bling fizzle, sizzle ullamcorper sure for sure nizzle sizzle. </p> 

	<div class="post-info">
		<ul>
			<li class="date">18th August 2011</li>
			<li class="category">Posted in <a href="#">Reviews</a></li>
			<li class="read-more"><a href="#">Read more</a></li>
		</ul>
	</div>

</div>

Each individual post is then enclosed in its own div to separate each one from the next. The next level heading of <h2> is used on post titles and the post thumbnail images can be easily inserted with an image tag inside an anchor. Some gansgter lorem ipsum dummy text fleshes out a brief sample post so we can see how the text will wrap, then the series of post info snippets are included as an unordered list.
In order to recreate the double border effect in the design concept we’ll have to commit a slight semantics faux-pas and nest this <ul> in a div to give ourselves another element to attach a border too. I guess another solution would be to use the CSS3 border-image property to add a tiny white/grey border effect around the elements.

<div class="pagination">
	<p class="prev"><a href="#">Older articles</a></p>
	<p class="next"><a href="#">Newer articles</a></p>
</div>

Underneath the posts will be a couple of pagination buttons to allow the user to browse back and forth between the archives. Another <ul> would be the best element to use, but WordPress tends to hide the <li> elements when they aren’t required, which leaves you with invalid code. The use of two separate paragraph elements is a much safer option.

<div id="side">
	<ul id="pages">
		<li><a href="#">Home</a></li>
		<li><a href="#">About</a></li>
		<li><a href="#">Archives</a></li>
		<li><a href="#">Contact</a></li>
	</ul>

	<h3>Categories</h3>
	<ul id="categories">
		<li><a href="#">Movies</a></li>
		<li><a href="#">Reviews</a></li>
		<li><a href="#">Articles</a></li>
	</ul>

	<h3>Search</h3>

	<form method="get" id="search" action="#">
		<fieldset>
			<input type="text" class="searchbar" />
			<input type="button" class="searchbutton" value="Search" />
		</fieldset>
	</form>

	<h3>About</h3>

	<p>Ticket Stub is a WordPress Theme based on the idea of a movie reviews site, but the overall design and layout makes the theme a perfect choice for any type of blog. <a href="#">Read more&hellip;</a></p>

</div>

The sidebar mostly includes lists of pages and categories, which obviously fit perfectly as unordered list elements. Our next level of heading is a <h3>, which separates the different sections in the sidebar. A simple form comprising of a single text input and button creates the search form, then the sidebar is finished off with a brief “About” paragraph.

<div id="footer">
	<ul id="credits">
		<li class="wordpress"><a href="http://wordpress.org">Powered by WordPress</a></li>
		<li class="spoongraphics"><a href="http://www.blog.spoongraphics.co.uk">Theme by SpoonGraphics</a></li>
	</ul>

	<p id="back-top"><a href="#">Back to top</a></p>
</div>

The HTML document is finished off with a simple footer div containing credit links and a back to top link.

The Complete HTML

View the annotated HTML

The CSS Styling

body, div, h1, h2, h3, h4, h5, h6, p, ul, ol, li, dl, dt, dd, img, form, fieldset, input, textarea, blockquote {
	margin: 0; padding: 0; border: 0;
}

body {
	font: 14px/24px Helvetica, Sans-Serif; color: #7e7e7e;
	background: #f5f5f5 url(images/bg.png);
}

a {
	color: #9f3a3a; text-decoration: none;
}
	a:hover {
		color: #792323;
	}

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

With the HTML structure in place we can now begin styling it up with CSS. The CSS file begins with a quick reset, then outlines the global font and background styling on the body element. All links in the design will use the same colour, so these can be listed with no specificity to capture every anchor in the document. The container div that wraps the page is given a 960px width and is centred up with auto margins.

#header {
	overflow: hidden;
}
	#header #logo {
		margin: 20px 0 10px 15px; float: left;
	}

	#header #subscribe {
		list-style: none; float: right; margin: 35px 30px 0 0;
		font-size: 16px;
	}
		#header #subscribe li.rss {
			background: url(images/rss-icon.png) left no-repeat;
			padding: 5px 0 5px 40px; margin: 0 0 10px 0;
		}
		#header #subscribe li.twitter {
			background: url(images/twitter-icon.png) left no-repeat;
			padding: 5px 0 5px 40px;
		}

Our header will contain two floated elements, so adding the overflow: hidden declaration will automatically clear the floats. The logo and subscribe buttons are moved into place with various margins, then the classes on each <li> item can be targeted to add the relevant icon to each respective link.

#main {
	background: url(images/faux.png);
	border: 1px solid #e6e6e6;
	overflow: hidden;
	box-shadow: 0px 0px 5px #d8d8d8;
	-moz-box-shadow: 0px 0px 5px #d8d8d8;
	-webkit-box-shadow: 0px 0px 5px #d8d8d8;

	border-bottom: 15px solid #fff;
}

In our design the sidebar has a grey background colour. An initial thought was to simply add this background colour to the #side div, but in the design the column extends all the way to the bottom of the page. The easiest way to replicate this is CSS is using the popular faux columns approach, where a sample image is used as a background image to create the impression of the two background colours. These days we can easily use CSS3 box-shadow to recreate a Photoshop shadow effect without the use of image files.
One problem with our faux columns is they fill the whole area of the div, whereas in the design we have a 15px border. We can replicate this border using the border property on both the #main and #side divs.

#main #content {
	width: 590px; float: left; padding: 35px 30px 60px 30px;
}
	#main #content h2 {
		font-size: 24px; font-weight: normal; text-transform: uppercase;
		margin: 0 0 15px 0;
	}

	#main p {
		margin: 0 0 24px 0;
	}

	#main #content .post-thumbnail {
		float: left; margin: 4px 30px 10px 0;
	}
		#main #content .post-thumbnail img {
			padding: 1px; border: 1px solid #eaeaea;
		}

The first of the two columns is given the larger width and floated to the left. Padding helps push the content into place away from the edges to match the Photoshop design. CSS typography helps set up the font styling to match the concept, using properties such as text-transform to revert text to uppercase even if it’s lowercase in the HTML. The post thumbnail image is floated into place alongside the content and is given a double border effect by combining 1px padding with a 1px border.

#main #content .post-info {
	padding: 1px; border: 1px solid #e9e9e9; margin: 0 0 60px 0;
}
	#main #content .post-info ul {
		background: #e9e9e9; list-style: none; text-transform: uppercase;
		padding: 15px 20px 10px 20px; overflow: hidden;
	}
		#main #content .post-info ul li.date {
			float: left;
		}
		#main #content .post-info ul li.category {
			float: left; margin: 0 0 0 20px;
			background: url(images/star.png) left no-repeat; padding: 0 0 0 35px;
		}
		#main #content .post-info ul li.read-more {
			float: right;
		}

In order to create the double border effect on the .post-info elements we’ll have to split the two border effects between the two items. The unique classes on the three list items then allow us to style and move each one exactly into position.

#main #content .pagination {
	overflow: hidden; margin: 0 0 60px 0;
}
	#main #content .pagination p {
		width: 180px; border: 1px solid #e9e9e9; padding: 1px;
		text-align: center;
	}
		#main #content .pagination p.prev { float: left; }
		#main #content .pagination p.next { float: right; }
		#main #content .pagination p a {
			display: block; background: #e9e9e9; padding: 15px 0px 10px 0px;
			text-transform: uppercase;
		}

Similar CSS styling can be used to style up the pagination buttons. They use the same double border effect, so the mix of background and border between an element and its child element are this time added to the <p> and <a> elements. Each button is then floated to the left or right, so the overflow: hidden; declaration is used on the parent element again to clear the floats.

#main #side {
	width: 263px; float: left; padding: 15px 30px 15px 15px;
	border-top: 15px solid white;
}	

	#main #side ul#pages, #main #side ul#categories {
		list-style: none; margin: 0 0 30px 0;
	}
		#main #side ul#pages li, #main #side ul#categories li {
			border: 1px solid #e9e9e9; padding: 1px;
			margin: 0 0 10px 0; text-align: right;
		}
			#main #side ul#pages li a, #main #side ul#categories li a {
				display: block; background: #e9e9e9; padding: 15px 20px 10px 20px;
				text-transform: uppercase;
			}

The second column of #side is given the narrower width and is also floated to the left. The buttons listing the pages and categories also employ the same double border effect, so the same code can be implemented on the <ul> and <li> elements. The only modification is the text is aligned to the right in this case.

#main #side h3 {
	font-size: 20px; font-weight: normal; text-transform: uppercase;
	margin: 0 0 10px 0; text-align: center;
}			

#main #side form {
	overflow: hidden; margin: 0 0 30px 0;
}
	#main #side input.searchbar {
		float: left; width: 193px; height: 25px; padding: 8px 13px 6px 13px;
		background: #fff; border: 1px solid #e9e9e9;
		font: 14px Helvetica, Sans-Serif; color: #7e7e7e;
	}
	#main #side input.searchbutton {
		width: 34px; height: 34px; float: left; margin: 3px 0 0 8px;
		background: url(images/search-icon.png); text-indent: -9999px;
		cursor: pointer;

		padding: 0 0 0 34px; /*IE Fix*/
	}

A quick series of declarations style up the <h3> titles in the sidebar at a slightly smaller size, then the search form is styled to match the original design concept. The search bar is replicated with a grey border, then padding and font styling helps turn the field into a fully working input. The search button on the other hand is styled using CSS image replacement, adding the icon image in place of the original text.

#footer {
	overflow: hidden; margin: 0 0 60px 0;
}
	#footer #credits {
		list-style: none; margin: 20px 0 0 30px;
	}
		#footer #credits li {
			float: left; margin: 0 6px 0 0;
		}
			#footer #credits li.wordpress a {
				display: block; width: 20px; height: 20px;
				background: url(images/credits.png) no-repeat 0 0; text-indent: -9999px;
			}
			#footer #credits li.spoongraphics a {
				display: block; width: 25px; height: 20px;
				background: url(images/credits.png) no-repeat -30px 0; text-indent: -9999px;
			}

	#footer p#back-top {
		float: right; margin: 0 30px 0 0;
	}
		#footer p#back-top a {
			display: block; padding: 0 0 0 26px;
			background: url(images/back-top-icon.png) left no-repeat;
		}

The only section of the design left to style up is the footer. The two credit icons are created using CSS image replacement while the back to top link to floated to the right.

Browser Testing

A quick test in the popular browsers shows no problems in Firefox, Safari and Chrome, but as usual Internet Explorer gets its panties in a twist. Thankfully it doesn’t require too much work to set it back on track.

<!--[if IE 6]>
	<link href="css/ie6.css" rel="stylesheet" />
<![endif]-->

We first need to create a special CSS stylesheet solely for IE6. A link to a separate CSS file is added inside conditional comments which only target Internet Explorer version 6.

#main {
	clear: both; height: 100%;
}

#main #content .post-info ul {
	height: 100%;
}

These days fixing up a website for IE6 is often more trouble than it’s worth, but in some cases only a couple of tweaks are required. In the case of this design the only problems we run into is the infamous double margin bug and some strange height issue. Both are easily fixed with the addition of a height: 100%; declaration.

The Final HTML/CSS Mockup

View the HTML and CSS website prototype

We now have our original concept coded up into a static HTML and CSS prototype so we can see how it looks and performs in various browsers before moving on to the next stage of building a fully working WordPress theme. Check out the mockup and stick around for the final tutorial where we’ll continue building that complete theme.

View the HTML/CSS prototype demo

August 24 2011

10:00

Simon’s Google Doodle – HTML5 + JS jQuery Game

Dude, you’ve heard a lot about Google doodles haven’t you? What about that Pacman one? It is just addictive. Company owners know how a funny game and unlimited search powers could be dangerous for productivity. And how it can be a marketing boost. The most amazing thing is that we can create our own addictive HTML game. Actually, this is why we are here today. With this tutorial you’ll see how to use some of JavaScript and HTML capabilities to build simple yet funny games.

So, let’s rock!

Demo first, please

You can download or try our online demo. Please, don’t forget to come back here if you want to just go playing first :)

“Well, actually I don’t know what a Doodle is..”

Google Doodles started when Larry and Sergey played with the corporate logo to indicate their attendance at the Burning Man festival in the Nevada desert. Since that day we’ve seen a lot of funny Doodles, and Google’s homepage is used to remind us of all kind of important facts.

But they are more than just paintings, games or experiments. They are made with the best current practices (some of them, created specifically for a Doodle). And Google being as supportive as they are of open source technology, usually release the commented source code, so you can just take a look and try to understand what those amazing guys are doing.

Oh, and I don’t know if you knew about it, but today is Simon’s day according to 1stWebdesigner’s official fake holiday calendar. Seems important, right? This is why we’ll build a game for it.

So, what will we be doing?

Simon is one of my favorite games (just after Sudoku and Gammon). Can you think of an easier game to code? You know, four buttons, easy actions. I just can’t think of a better starting point to learn HTML5 gaming.

Well, first of all you need to know what this Simon thing looks like. I just found a picture of it at Mercado Livre (kind of a Brazilian e-bay) and made my own version in Photoshop.

Since we are doing it via HTML5, the colors shouldn’t be directly on image (otherwise you won’t be able to change colors, make your own console…). So I’ve used Chris Coyier‘s technique for color animation. Basically we make our non-colored elements, and leave everything else transparent. Then our HTML5 will take care of the color itself (via CSS, background-color). Our final game background will be something like this:

Ok, then. Let’s start the fun part.

Basic HTML + CSS

Since our target isn’t basic HTML itself, I just grab a copy of HTML5 Boilerplate with a few edits to make it cleaner:

[php]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">

<title>Google.com – Simon’s day (1stWebDesigner.com game :D)</title>

<link rel="stylesheet" href="css/style.css?v=2">
<script src="js/libs/modernizr-1.7.min.js"></script>
</head>
<body>
<div id="container">
<div id="main">
<!– Game controls and deisgn –>
</div>
<form id="search" action="#" method="get">
<input type="text" name="query" id="query" />
<input type="submit" value="search" id="submit" />
</form>
<div id="options">
<!– game options –>
</div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
<script src="js/script.js"></script>
</body>
</html>
[/php]

Now we need our gaming HTML stuff. As we’ve done it ready for different colors we will need to have two layers:

  • Background color- sets the color and will be animated when you activate a button
  • Link – activates all actions for each colored button.
  • Alerts – since they are part of the game itself, we’ll put them with all other game controls (level up, new game, game over)

Our HTML for this part will be something like this:

[php]
<div id="main">
<!– lights –>
<div id="box-0" class="box">&nbsp;</div>
<div id="box-1" class="box">&nbsp;</div>
<div id="box-2" class="box">&nbsp;</div>
<div id="box-3" class="box">&nbsp;</div>
<!– buttons –>
<a href="#" class="box btnTL" id="box-click-0">&nbsp;</a>
<a href="#" class="box btnTR" id="box-click-1">&nbsp;</a>
<a href="#" class="box btnBL" id="box-click-2">&nbsp;</a>
<a href="#" class="box btnBR" id="box-click-3">&nbsp;</a>
<!– alerts –>
<div id="letsRock" class="alert">
<p>Ready? let’s rock!</p>
</div>
<div id="ohYes" class="alert">
<p>Oh Yeah!</p>
</div>
<div id="ohNoes" class="alert">
<p>Oh Noes… Almost there! </p>
</div>
</div>
[/php]

As you can see, the four “div.box” elements are the background color for each button (red, blue, green, red).

So when someone clicks #box-click-0 it will “activate” the button #box-0. We have a lot of id’s because they result in better JS performance.

Our CSS for that will be:

[php]
#main {
position: relative;
left: 155px;
width: 200px;
height: 200px;
}
.box {
display: block;
float: left;
width: 100px;
height: 100px;
}
a.box {
position: absolute;
text-decoration: none;
background-image: url("../img/bg_game.png");
background-repeat: no-repeat;
}
a.box:focus {
outline: none;
}
.btnTL { background-position: top left; }
.btnTR { background-position: top right; }
.btnBL { background-position: bottom left; }
.btnBR { background-position: bottom right; }
.btnTL, .btnTR {
top: 0;
}
.btnBL, .btnBR {
bottom: 0;
}
.btnTL, .btnBL {
left: 0;
}
.btnTR, .btnBR {
right: 0;
}
#box-0 {
background: #c00000;
}
#box-1 {
background: #1506a3;
}
#box-2 {
background: #046606;
}
#box-3 {
background: #ea8f0c;
}
[/php]

Here is our effect: all our links have the console background, bg_game.png (positioned according to what it should be, of course). Since they are on top of divs, what we will see is the bg_game.png AND the element’s color ( #c00000, #1506a3…).

Ok, we won’t be long on this. Maybe this is enough topic for a single article :)

Search form

Have you noticed the recent (ok, maybe not that recent) Google’s switch to real time results? That’s pretty cool, yeah, I know. But it makes a little bit harder to link directly to a search results page.

Since our demo has a search form and we want to make it work, let’s put a little JS magic on it:

[php]
<form id="search" action="#" method="get">
<input type="text" name="query" id="query" />
<input type="submit" value="search" id="submit" />
</form>
[/php]

Javascript:

[php]
$(function(){
$("#search").submit( function(event) { event.preventDefault(); googleRedirect(); } );
});
function googleRedirect() {
var query = $("#query").attr(‘value’);
var url = "http://www.google.com/#q=" + query + "&fp=1";
window.location = url;
}
[/php]

This way it will work ;)

Cookies? No, no, local storage instead!

Well, Cookies are great for some things, but this time they aren’t the very best option. Here we will make use of Local Storage. This is basically the same idea as Cookies, it allows you to store data related to your site, the difference is that it’s faster and very useful in some situations.

As its name suggest it is local, so it won’t be sent to the server (you save a few kbytes and processing). Cookies are limited to 4kB and 20 Cookies per domain. With local storage you can record up to 5MB of user data.

The only downside is that it works only on real browsers and IE8+. So, forget about IE7 this time (maybe later with some jQuery data fallback).

Another huge advantage is that it is surprisingly easy to set / remove;

[php]
localStorage["level"] = 15; // create it with 15 as value
var level = localStorage["level"]; //now var level is 15
localStorage.removeItem( "level" ); //remove it!
[/php]

So, this is why we will use it this time.

A few options

Then we need to have a way to start the game, see which level we’re playing, these sort of trivial things. For this, we’ll just put a simple HTML box with Google’s logo:

[php]
<div id="options">
<ul>
<li>Level: <span id="levelCount">1</span></li>
<li><a href="#" onclick="newGame()" >New Game</a></li>
<li>High Score: <span id="hs">1</span></li>
<li><a href="http://www.1stwebdesigner.com" target="_blank" >Credits</a></li>
</ul>
</div>
[/php]

Well, what is important here is that our counters have id’s wrapping them, so we can easily change their text.

Let the game begin

Random sequence

The very first thing to do when you start this game should be to generate a random sequence. Because this sequence will be the “right path” to be followed by players. We could generate it on-the-fly as our gamer reaches new levels, but it will be easier to do this way.

So we will create a simple function that just generate a random sequence with 50 digits (levels) and only with numbers from 0 to 3 (our colors!):

[php]
function randomSequence() {
var chars = "0123"; // four colors!
var string_length = 50; //pretty hard, isn’t it?
var sequence = "";
for (var i=0; i < string_length; i++) { //we’ll have from sequence[0] to sequence[49]
var rnum = Math.floor(Math.random() * chars.length);
sequence += chars.substring(rnum,rnum+1);
}
return sequence;
}
[/php]

Binding clicks and hovers

Now we need to prepare our all a.box elements to recognize clicks and to animate properly our div.box when you hover any of them.

This time we will need jQuery .hover() and .click() functions:

[php]
$(function(){
//caching our elements for better performance
box0 = $("#box-0");
box1 = $("#box-1");
box2 = $("#box-2");
box3 = $("#box-3");
clickbox0 = $("#box-click-0");
clickbox1 = $("#box-click-1");
clickbox2 = $("#box-click-2");
clickbox3 = $("#box-click-3");
clickbox0.click(
function(event){
event.preventDefault();
clicked(0);
}
);
clickbox1.click(
function(event){
event.preventDefault();
clicked(1);
}
);
clickbox2.click(
function(event){
event.preventDefault();
clicked(2);
}
);
clickbox3.click(
function(event){
event.preventDefault();
clicked(3);
}
);
var minHover = 0.7;
var maxHover = 1;
var timeHover = 500;
clickbox0.hover(
function(){
box0.stop().animate({opacity: minHover}, timeHover);
}, function() {
box0.stop().animate({opacity: maxHover}, timeHover);
}
);
clickbox1.hover(
function(){
box1.stop().animate({opacity: minHover}, timeHover);
}, function() {
box1.stop().animate({opacity: maxHover}, timeHover);
}
);
clickbox2.hover(
function(){
box2.stop().animate({opacity: minHover}, timeHover);
}, function() {
box2.stop().animate({opacity: maxHover}, timeHover);
}
);
clickbox3.hover(
function(){
box3.stop().animate({opacity: minHover}, timeHover);
}, function() {
box3.stop().animate({opacity: maxHover}, timeHover);
}
);
});
[/php]

It is pretty important caching all our elements, since it improves a lot our performance.

Magical JS variable variables and easy error detection

At this point you have coded all the hover and click elements, but when you click them nothing happens, of course. Let’s fix it:

[php]
// yeah, someone is playing it!
function clicked( color ) {
// refresh my memory, how long have you gone so far?
var level = localStorage["level"]; // this is our current level
var clicks = localStorage["clicks"]; //this is our current item INSIDE one level
var speed = localStorage["speed"]; //to make it more fun, when you get right it goes faster
// blink it!
window['box' + color].stop().animate({ opacity: 0.3 }, (speed * 0.5) ).animate({ "opacity": "1" }, (speed * 0.3) ); //variable variables in js via window[varname] :)
// well, this time you’ve got it right?
if ( localStorage["sequence"][clicks] == color) {
//oh, yeah!
localStorage["clicks"]++;
//have you finished this level?
if ( level == clicks) {
nextLevel();
}
} else {
//oh, noes!
endGame();
}
}
[/php]

Every variable in javascript can be accessed via its own name, like box1 OR as an index inside window array, just like window['box1']. With this we can easily select which is the right element to blink (when you click any button, it should blink, right?).

Ok, you are right! Let’s go to the next level

When you get it right, the game should get you to the next level and the events should accelerate a little bit.

Then when you get it right you should also know which is the right sequence at your current level + 1, so let’s do it:

[php]
function nextLevel() {
//Oh, Yes
showBox("#ohYes", 1000);
// you deserve it, let’s move on
localStorage["level"]++;
levelCount.text(localStorage["level"]);

localStorage["clicks"] = 0;
//let’s show you how it’ll be
current = 0; //since it’s used just for animation, let’s leave it as global var
if ( localStorage["speed"] > 300 && (localStorage["level"] / 5) == 0 ) { //our maximum speed, and we’ll only acelerate it each 5 levels
localStorage["speed"] = localStorage["speed"] * 0.8;
}
setTimeout( function() { rightPath(); } , localStorage["speed"] );
}
[/php]

Function showBox just shows our div and hides it after one second.

As you can see this piece of code isn’t complete, we will need the function rightPath() to see what comes next. Let’s go:

[php]
function rightPath() {
if ( current <= localStorage["level"] ) {
var sel = localStorage["sequence"][current];
window['box' + sel].stop().animate({ "opacity": "0.5" }, (localStorage["speed"] * 0.5) ).animate({ "opacity": "1" }, (localStorage["speed"] * 0.3) );
setTimeout(
function() {
rightPath();
},
(localStorage["speed"] * (1.5) )
);
current++;
}
for (var i=0; i <= localStorage["level"] ; i++) {
var time = 1000 * (i + 1);
}
i = 0;
}
[/php]

This is kind of crazy, isn’t it? This is a simple recursive function. It will call itself, blink the right button for one position and then go to the next until we reach user’s current level.

What if you get it wrong?

Maybe instead of click the right button you can just click the wrong button. Then we need to punish you and ban you from the entire world wide web. Let’s see our function for that:

[php]
function endGame() {
//let’s see if you have a high score, and save it
if ( localStorage["hs"] == undefined || localStorage["level"] > localStorage["hs"] ) {
localStorage["hs"] = localStorage["level"];
$("#hs").text(localStorage["hs"]);
}

localStorage.removeItem( "level" );
// Oh, noes!
showBox("#ohNoes", 2000);
}
[/php]

Well, here we just check if you’ve done something better than this play and then remove your current level so you can restart a new game and try a little harder :)

By the way, did I mention how will you start a game? No? Sorry, my bad.

Sorry, NOW the game will begin

What do we have to do in order to start a match is to reset almost anything we have here and then show what is the right path.

[php]
// just like starting over!
function newGame() {
current = 0;
levelCount.text(1);
//let’s call our sequence and memorize it
localStorage["sequence"] = randomSequence();
//wow, we haven’t got anything right until now :)
localStorage["level"] = 0;
//clicks binding
localStorage["clicks"] = 0;
//let’s make things slow for now
localStorage["speed"] = 1500;
//let’s show our welcome warning
showBox("#letsRock", 2000);
//and let’s show the first color
rightPath();
}
[/php]

What is your best score?

Hope you enjoy this quick HTML5 game tutorial and that you find some easter eggs, you know, since it’s a JS game we can’t hide a lot of things on it :)

But the most important thing here is: what is your best score?

August 23 2011

21:00

Mastering Markdown: 30 Resources, Apps and Tutorials to Get You Started

If you’re like me, learning Markdown has been on your todo list for months. I finally took the plunge and instantly became addicted to sorting through the wealth of resources, apps and other Markdown related materials available.

The following is a collection of the best Markdown resources that I’ve found. Whether you’re a complete Markdown newbie looking to learn the syntax or a seasoned expert in the market for a new iPad app, you’ll find something here that’s perfect for your needs.


Like the article? Be sure to subscribe to our RSS feed and follow us on Twitter to stay up on recent content.

What Is Markdown?

Markdown is a markup language that was created by John Gruber to simplify the workflow of web writers. Many bloggers, like myself, usually write our posts in straight HTML, which can be cumbersome and difficult to read through. Markdown provides a much simpler and easier to read alternative that can easily and instantly be converted to HTML using any number of free tools.

If you’re a writer and you constantly use HTML, Markdown is for you. If not, you might just find it to be absolutely useless. I personally really like the syntax and find it to be quite intuitive. Take a look at the resources below and see what you think!

Learning Resources

Markdown

Here’s the gist on Markdown straight from the source. Gruber introduces the concept, outlines its use and syntax and even provides a Pearl plugin that works with Movable Type, Blosxom, and BBEdit.

screenshot

Slekx Interactive Tutorial

Normal tutorials are boring, check out this interactive tutorial and you’ll pick up the Markdown Syntax in no time. You will be editing the actual text of the tutorial, adding Markdown elements as you learn them. Markup elements are reused throughout the tutorial in order to ingrain the Markdown that you’re learning.

screenshot

Markdown: An Introduction

This is a super short and simple introduction to Markdown without all the fluff. If you have at least a double-digit IQ, you can probably pick up Markdown in under two minutes by browsing through this tutorial.

screenshot

Video Markdown Tutorial

If reading makes your eyes sleepy and you prefer a video tutorial, here’s one from Stevan Wing. It’s a really in-depth look that walks you through the concept, syntax and implementation.

screenshot

Multimarkdown

MMD is a superset of the Markdown syntax. It adds multiple syntax features (tables, footnotes, and citations, to name a few), in addition to the various output formats listed above (Markdown only creates HTML). Additionally, it builds in “smart” typography for various languages (proper left- and right-sided quotes, for example).

MultiMarkdown Introduction PDF Presentation

screenshot

MultiMarkdown Syntax Guide

A GitHub hosted guide to the markup syntax used in the MultiMarkdown system.

screenshot

Cheat Sheets

WarpedVisions Markdown cheat sheet

A short sheet of the Markdown, Markdown Extra, and SimpleLink syntax.

screenshot

Mashery Markdown Cheat Sheet

This web page contains a bunch of nicely formatted tables that showcase examples of Markdown syntax and the resulting output.

screenshot

Squarespace Markdown Syntax Reference

A simple, no frills Markdown reference sheet from Squarespace.

screenshot

Ahren Code Markdown Cheatsheet

Instead of a web page, this one comes as a PDF that you can download. As you can see below, it has an interesting dark visual theme.

screenshot

Scott Boms Markdown Syntax Cheatsheet

If you didn’t like the dark theme of the previous PDF, here’s one with a much simpler, more typography-driven design.

screenshot

Jeremy Stretch’s Markdown Cheat Sheet

A dense but nicely organized cheat sheet perfect for printing as a desk reference.

screenshot

Station in the Metro Markdown Syntax Cheat Sheet

A very thorough, two page PDF cheatsheet.

screenshot

Mac Apps

Byword

A really nice full-screen text editor with Markdown support. Byword is currently $9.99.

screenshot

Marked

Marked opens MultiMarkdown, Markdown, Text or HTML files and previews them as HTML documents. It watches the file for changes, updating the preview any time the file is saved. With a full set of customization options and preview styles, Marked adds an ideal “live” Markdown preview to any text editor. Marked is $2.99.

screenshot

Macchiato

Macchiato is a simple plain text editor with a twist. Modeled after TextEdit’s plain text mode, the editor is a chrome-less blank canvas. However, it is built from the ground up for writing Markdown prose—and, as such, it will format Markdown text as you write it. Macchiato will not *parse* your Markdown. Rather, it will *stylize* your Markdown source. Macchiato is $14.99.

screenshot

MarkMyWords

MarkMyWords is a powerhouse of functionality for Markdown users. It’s not the prettiest app out there but it’s by far the most fully-featured Markdown client I’ve ever seen. MarkMyWords is $24.99.

screenshot

IA Writer

IA Writer is one of the best apps in the full-screen text editor genre. The interface is gorgeously simple and the app has some excellent auto Markdown functionality built in. IA Writer is $9.99.

screenshot

nvALT

nvALT is a fork of the original Notational Velocity with some additional features and interface modifications, including MultiMarkdown functionality. nvALT is a free download.

screenshot

iOS Apps

Elements (iPhone and iPad)

Elements is a dedicated Markdown and Dropbox powered text editor for iOS. Elements allows you to view, edit and share plain text documents on your iPad, iPhone or iPod touch. All of your data is stored in a folder on your personal Dropbox account so that it’s accessible from any device you have. Elements is $4.99.

screenshot

Nocs (iPhone & iPad)

With integration to Dropbox, Markdown, and a text editor, Nocs lets you work with your documents on any iDevice. Nocs is $2.99.

screenshot

WritingKit (iPad)

Link to Dropbox. Write Markdown-formatted text. Use your favorite TextExpander snippets. Do quick research to find reference materials. Insert quotes and links into your documents. Upload images to CloudApp. Export your writings as Markdown or HTML files. Do all this and more with this awesome iPad text editor. WritingKit is $4.99

screenshot

MarkdownNote (iPad)

MarkdownNote makes it really easy to create notes using Markdown. Using live preview feature, you can preview your Markdown markup syntax to HTML. MarkdownNote is $3.99.

screenshot

Windows Apps

Writemonkey

Writemonkey is a free app that’s a lot like Writeroom for Windows. Writemonkey supports Markdown and Textile markup standards.

screenshot

Sublime Text

Sublime Text is a powerful Windows text editor with, among many other things, Markdown support. Sublime Text is $59.

screenshot

Free Web Apps

Markdown Dingus

The official online Markdown Converter from Daring Fireball. Simply paste in your text and get both the HTML output and a preview. There’s also a handy cheat sheet on the right side of the page.

screenshot

Jon Combe Markdown Editor

This is one of my favorite online Markdown editors. It’s nice and simple with just the right amount of options and zero clutter. I love the two window mode that lets you see the HTML preview of your Markdown as you type. You can then download the HTML and/or Markdown versions.

screenshot

CtrlShift.net Markdown Editor

Like the previous link, this tool has a two window setup that lets you view the output as you type.

screenshot

Hashify

This one is new to me but I already really like it. It updates the preview live as you type like the previous two links but places a much larger visual emphasis on the output with a huge preview. There’s also a tweet button and even a QR code generator for your result, how cool is that?

screenshot

Backpager

Yet another two window Markdown Editor with options to preview either source or syntax.

screenshot

Alternatives

Markdown fits into a category known as Lightweight markup languages, and it’s by no means the only one. If you’re looking for others, Wikipedia has a stellar feature by feature comparison of all of the popular options such as Markdown, Textile, txt2tags and more.

Conclusion

That concludes our roundup of Markdown resources. If you’re just starting your Markdown journey, bookmark this page as your one-stop-shop for everything you need to know and download.

Leave a comment below and let us know what you think of Markdown. Have you ever tried it? Do you use it frequently? What resources and apps have you found to be helpful?

Tags: HTML

August 15 2011

12:00

Introduction to HTML5 Web Storage

Advertise here with BSA


Introduction to HTML5 Web Storage

Web Storage is a new HTML5 API offering important benefits over traditional cookies. Although the specification is still in W3C draft status, all major browsers support it already.

This means you can start using the API’s sessionStorage and localStorage objects (we will discuss these later on) and enjoy their benefits.

The Limitations of Cookies

First, there were cookies. They have been a huge driving factor for the Web since the early days. In both a good and a bad way.

For example, cookies allow us to login automatically to sites we use frequently, such as Gmail and Facebook.

On the other hand, with cookies, our search and browsing history can be tracked and our privacy is a concern.

Another problem with cookies is that they have data-capacity limitations. The data storage limit of cookies in many web browsers is about 4 KB per cookie, based on a deprecated 1997 specification recommending a minimum of 4096 bytes per cookie.

Although most browsers allow 30 to 50 cookies, so if you exceed the 4 KB limit of one cookie you could create another one, this is still a real limitation.

This is why developers usually only store user and/or session identifiers in cookies, and then use server-side databases to store and get the rest of the user data.

Additionally, an often-overlooked side effect of cookies is that they are always sent with every HTTP request (usually even for images) resulting in more data being sent over the wire.

Moving Forward with Web Storage

Web Storage picks up where cookies left off. The strength of Web Storage is in at least two things.

First, ease of use for web developers: It has a simple API to get and set key/value pairs (we will get more into this below).

Secondly, the amount of space it provides: the specs default the disk space quota decision to the user agent (i.e. the web browser developers) and most of them offer no less than 5 or 10 MB to be stored per domain. This means we can store more than just basic user/session info on the client-side: user preference settings, localization data, temporary offline storage for batching server writes and much more.

The data being stored can be accessed using JavaScript, which gives you the ability to leverage client-side scripting to do many things that have traditionally involved server-side programming and relational databases.

Session Storage and Local Storage

It is important to know that there are two types of Web Storage objects: sessionStorage and localStorage.

sessionStorage is only available within the browser tab or window session. It’s designed to store data in a single web page session.

localStorage is kept even between browser sessions. This means data is still available when the browser is closed and reopened, and also instantly between tabs and windows.

Web Storage data is, in both cases, not available between different browsers. For example, storage objects created in Firefox cannot be accessed in Internet Explorer, exactly like cookies.

Where to Use Web Storage

Some examples of implementation scenarios include storing the data for an online to-do list (then pushing to the server in intervals instead of in real-time) or saving products that the user places in his shopping cart. The data can be made available between page requests, multiple browser tabs, and also between browser sessions using localStorage.

Your apps can actually be used offline completely using localStorage. Data can then be sent and stored server-side when the user is online again.

From another perspective, Web Storage can be a great performance win when some static data is stored on the client to minimize the number of subsequent requests. Even images can be stored in strings using Base64 encoding.

For the examples mentioned above, it makes sense to use localStorage. You may be wondering, then, when you should opt for sessionStorage.

In some cases, you simply want to get rid of the data as soon as the window is closed. Or, perhaps, you don’t want the application to interfere with the same application that’s open in another window (e.g. when running two instances of a Scrabble game or running multiple unit tests simultaneously, you don’t want data to collide). These scenarios are served best with sessionStorage.

Using the Web Storage API

It’s really simple. It’s probably best just to show it:

sessionStorage.setItem('myKey', 'myValue');
var myVar = sessionStorage.getItem('myKey');

localStorage.setItem('myKey', 'myValue');
var myVar = localStorage.getItem('myKey');

Note that the interface for creating sessionStorage and localStorage is identical and that they are global objects.

You can use the .setItem method to set the key and its value, and then .getItem to retrieve the value of a specific key.

Note that we can only store strings, which is a significant drawback. However, to get around this, we can store and retrieve string representations of JSON objects by using the JSON.stringify() method to store a string, and JSON.parse() to create the original object from that string.

Web Storage Events

Whenever we store data in localStorage, the storage event is fired in other browser windows/tabs.

What is so great about that?

This event can be used to overcome that so-called race conditions between browser windows/tabs: If the user has the same site open in different tabs, this event can be used to synchronize the data. (This was actually quite an issue with cookies.)

The storage event is only fired when the new value is not the same as the old value. The storage event contains the key, oldValue and newValue properties of data that has changed, which you can access in code.

Example code:

window.addEventListener('storage', function(event) {
  console.log('The value for ' + event.key + ' was changed from' + event.oldValue + ' to ' + event.newValue);
  }, false);

Above, we create an event listener on the window object for the storage event. When the event happens, a function that logs the key, oldValue and newValue to your console (e.g. Firebug or Google Chrome Developer Tools) is executed.

Browser Support for Web Storage

You are encouraged to start using this API today. Web Storage is implemented in IE8 and in all modern browsers (i.e. starting from Firefox 3.5, Safari 4, Google Chrome 4, and Opera 10.50).

The storage event was added later, but is available in at least Firefox 5, Safari 5, Chrome 12, Opera 10.5 and reportedly in IE9.

Security Concerns

Please be aware that using Web Storage is really not more secure than cookies. With greater power, comes greater responsibility.

SSL does a great deal of resolving security issues. (SSL means the client and server communicate only encrypted data). This is why you see more and more websites using the more secure https protocol.

In any case, do not store sensitive data (like passwords and credit card numbers) on the client-side, nor send this kind of data to the client.

Final Notes

Web Storage is sometimes referred to as DOM Storage, this is the same thing. The latter is derived from the fact that the data is actually stored in JavaScript’s window object (i.e. window.localStorage and window.sessionStorage).

And last but not least, keep in mind that Web Storage, just like cookies, can be turned off by the user. So you always need to implement a fallback mechanism in case window.sessionStorage or window.localStorage is not available.

Further Reading

Related Content

About the Author

Lars Kappert is a front-end web developer and IT specialist from the Netherlands. His development style focuses on pragmatism and creating web products for real-world scenarios. Visit his portfolio site: WebPro. Follow him on Twitter as @webprolific and connect with him on LinkedIn.

Tags: HTML

July 25 2011

07:00

How To Create a Slick Features Table in HTML & CSS

We’ve all grown up as web designers staying well away from table based layouts, but we don’t often brush up on our table building skills ready for when we will actually need them. Follow this step by step tutorial to create a slick looking data table to compare the features of various Harley Davidson motorcycles. We’ll build the table in clean HTML then polish it up with CSS to create a cool and easily readable HTML table.

Harley Davidson features table demo

The table we’ll be building compares a bunch of features between three Harley Davidson Sportster motorcycle models. Other than the slick design we’re putting together for the sake of this demo, the table will be built with clean HTML then styled with CSS to make the data easily readable.

View the final HTML/CSS features table

For the design of this particular demo there’s a few files we need from my original PSD concept. These include a patterned PNG graphic we’ll use as a background, the large black and white photo to fill up the demo background, the Harley Davidson logo and photos of the three bike models we’re comparing.

The demo file begins with a typical HTML structure including Doctype, page title and a link to the CSS stylesheet. The page content begins with a <h1>, which will later be converted to the HD logo, then a container div is added to help house and centre up the content.

Next the <table> element is inserted, followed by a <thead> to outline the titles and headings in our table. The <thead> contains two rows, one with the bike photos and the second with titles of each model in <h2> tags. The overall table has three columns, but the first cells in the header are empty so a &nbsp; character is added. To help us style the table and aid the readability of the table data while in code view relevant classes are added to the cells.

After the closing of the <thead> the <tbody> begins. Where <th> elements are used in the <thead>, <td> elements are used in the <tbody>. Each series of cells is contained within a row, and our classes help identify the different columns. All the rows of data are added to finish off the HTML.

The complete HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Harley Davidson Sportster Motorcycle Model Comparison</title>

<link href="style.css" rel="stylesheet" />

</head>

<body>

<h1>Harley Davidson Motorcycles</h1>

<div id="container">

	<table>
		<thead>
			<tr>
				<th>&nbsp;</th>
				<th class="iron"><img src="images/iron.jpg" alt="Harley Davidson Iron 883" /></th>
				<th class="nightster"><img src="images/nightster.jpg" alt="Harley Davidson Nightster" /></th>
				<th class="fortyeight"><img src="images/forty-eight.jpg" alt="Harley Davidson Forty-Eight" /></th>
			</tr>
			<tr>
				<th>&nbsp;</th>
				<th class="iron"><h2>Iron 883</h2></th>
				<th class="nightster"><h2>Nightster</h2></th>
				<th class="fortyeight"><h2>Forty-Eight</h2></th>
			</tr>
		</thead>

		<tbody>
			<tr>
				<td class="feature">Engine</td>
				<td class="iron">883cc</td>
				<td class="nightster">1202cc</td>
				<td class="fortyeight">1202cc</td>
			</tr>

			<tr>
				<td class="feature">Torque</td>
				<td class="iron">70Nm</td>
				<td class="nightster">98Nm</td>
				<td class="fortyeight">98Nm</td>
			</tr>

			<tr>
				<td class="feature">Exhaust</td>
				<td class="iron">Chrome, staggered shorty exhaust with dual mufflers</td>
				<td class="nightster">Chrome, slash-cut exhaust with dual mufflers</td>
				<td class="fortyeight">Chrome, staggered shorty exhaust with dual slash-cut mufflers</td>
			</tr>

			<tr>
				<td class="feature">Wheels</td>
				<td class="iron">Black, 13-Spoke Cast Aluminum</td>
				<td class="nightster">Black, Laced Steel</td>
				<td class="fortyeight">Black, Laced Steel</td>
			</tr>

			<tr>
				<td class="feature">Ground Clearance</td>
				<td class="iron">120mm</td>
				<td class="nightster">130mm</td>
				<td class="fortyeight">100mm</td>
			</tr>

			<tr>
				<td class="feature">Price</td>
				<td class="iron">£6,699</td>
				<td class="nightster">£8,099</td>
				<td class="fortyeight">£8,849</td>
			</tr>
		</tbody>

	</table>

</div>

</body>
</html>

The CSS begins with a simple CSS to remove any default browser styling, then the global styling for this particular demo file is set up. The large background image is added to the page body and overall font styling set up as 16px Georgia in grey.

The <h1> element is then converted to the Harley Davidson logo using the image replacement technique, then the container div is styled to sit centrally on the page. The patterned background image is used as a fill and a CSS3 box-shadow is created to replicate the Photoshop drop shadow effect.

By default the table displays with small gaps between the table cells. Our design requires a kind of margin between the columns but no gaps between the rows. The border-spacing property allows us to designate an exact amount of spacing on both the Y and X axis. Padding is added and text centred on all <th> and <td> elements, then this is overwritten for the cells with the class “feature”, sending the text back to left alignment. These cells are also given an exact width to alter the proportions of the table, making this column the largest.

Our classes of “iron”, “nightster” and “fortyeight” are all given a background fill of transparent white using RGBa colour selection. We could have used a single class for all these cells, but the name specific classes help us navigate the table data while in code view. To add a finishing touch to the table, the same transparent fill is also added to table rows, but only when they’re hovered by the user’s mouse. This simple effect boosts the usability of the table, helping the user easily cross reference and compare the data.

The complete CSS

body, div, h1, h2, h3, h4, h5, h6, p, ul, ol, li, dl, dt, dd, img, form, fieldset, input, textarea, blockquote, table, tr, td, th {
	margin: 0; padding: 0; border: 0;
}

body {
	background: #000 url(images/bg.jpg) center top fixed no-repeat;
	font: 16px Georgia, Serif; color: #ccc;
}

h1 {
	width: 168px; height: 130px; margin: 30px auto; position: relative;
	background: url(images/harley-davidson.png); text-indent: -9999px;
}

#container {
	width: 940px; margin: -115px auto; padding: 110px 10px 50px 10px;
	background: url(images/bg-pattern.png);
	box-shadow: 0px 0px 15px #000;
}

table {
	border-spacing: 10px 0px;
}

th, td {
	text-align: center; padding: 10px;
}

.feature {
	width: 183px; text-align: right;
	font-size: 24px; font-weight: normal; color: #fff;
}

.iron, .nightster, .fortyeight {
	background: rgba(255,255,255,0.05);
}

h2 {
	font-size: 24px; font-weight: normal; color: #fff;
}

tr:hover {
	background: rgba(255,255,255,0.05);
}
	thead tr:hover {
		background: none;
	}

The final HTML/CSS feature table

Harley Davidson features table demo

Check out the complete demo file to see the feature table in action with its hover effect. The use of transparency from the PNG24 files and RGBa colouring really helps create a sleek design when combined with the large background image. Overall these simple table styling techniques can be used on any project to display your tabular data in a readable and easily digestible manner.

View the feature table demo

July 22 2011

10:00

17 CSS/HTML Effects with Cross-Browsing Alternatives

Well, we surely have a lot of different ways to achieve similar effects and with CSS the hardest part is to make it look good in almost every browser.

You don’t need to reinvent the wheel every time, if you get one good snippet that does what you want (and you understand what is happening) you don’t need to reinvent it every time you need a simple round corner, right?

Thus, our point here is to collect some cool CSS effects that you should be using:

• Min / Max width (IE included)
• RGBA (IE included)
• Opacity (IE included)
• Image rotation / scaling (IE included)
• FullScreen Background (IE included)
• Background pattern or bullet without image file
• Text Shadow (IE included)
• Multiple borders (IE included)
• Box Shadows (IE included)
• Rounded corners
• Screen reader only accessible content
• Don’t use negative text-indent
• Clearfix (IE included)
• @font-face (IE included)
• Pull quotes without image
• CSS for iPhone4 (higher resolution)
• CSS landscape / portrait orientation for mobiles

So, Let’s rock!

Min / Max width (IE included)

Well, many of you are used to just replace the lack of min / max width / height for IE with fixed dimensions, right? But you don’t need to do it anymore. IE is not a strict standards browser and sometimes we can take advantage of this to code things that would be awful to see in standard CSS code.

You can, in this case, insert some IE expressions (basically, JavaScript code) to check current body width and adjust element’s width as follows:

#content {
	width: expression(document.body.clientWidth < 762? "760px" : document.body.clientWidth > 1242? "1240px" : "auto");
	min-width: 760px;
	max-width: 1240px;
}

RGBA (IE included)

This time we will need some IE filters to get the job done. You’ll have the standard markup, IE6 correction and IE8 correction.

IE corrections is based on gradient filter, that actually we put just one color to the beginning and the end, and BAM! We have a pretty RGBA background.

The first two digits should be the opacity and the last one should be the color itself. Don’t know why, it just don’t get the opacity right… Maybe its just a bug inside a bug :)

.element {
  background-color: transparent;
  background-color: rgba(255, 255, 255,0.8);
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#80ffffff,endColorstr=#80ffffff);
  -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#80ffffff,endColorstr=#80ffffff)";
}

Opacity (IE included)

Wow, filters again! But this time we have a different syntax for IE8 and earlier versions. And again be sure to put khtml, moz and standard declarations.

.selector {
	ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; /* internet explorer 8 */
	filter: alpha(opacity=50); /* internet explorer 5~7 */
	-khtml-opacity: 0.5;      /* khtml, old safari */
	-moz-opacity: 0.5;       /* mozilla, netscape */
	opacity: 0.5;           /* fx, safari, opera */
}

Image rotation / scaling (IE included)

Another pretty cool and virtually unused feature is image rotation / scaling. There is another filter that allows you to rotate images, but unfortunately it just allows you 90º increments.

Although you can also mirror images, that makes cool image editing possible to almost every real browser and IE. For real browsers we will use the transform property with each vendor prefix.

	img {
		transform:
			rotate(180deg)
			scale(-1, 1);

		/* for firefox, safari, chrome, etc. */
		-webkit-transform:
			rotate(180deg)
			scale(-1, 1);
		-moz-transform:
			rotate(180deg)
			scale(-1, 1);

		/* for ie */
		filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1);

		/* opera */
		-o-transform:
			rotate(180deg)
			scale(-1, 1);
	}

Fullscreen Background (IE included)

Sometimes we just need a quick way to get full screen backgrounds. Well, hope you don’t use JavaScript just to do this, because you can do it with a few lines of CSS.

The magic here is to set a div that goes fullscreen and inside it you can put a landscape, portrait or full sized image.

	.content {
		position: relative;
		width: 760px;
		z-index: 10;
	 }
	 .background {
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		position: absolute;
		z-index:2;
	 }
		.portrait {
			height: 100%;
		}
		.landscape {
			width: 100%;
		}
		.full {
			width: 100%;
			height: 100%;
		}
<div class="content">
	<p>aaaaaaaaaaaaaaaaaaaaaaaaaaaa</p>
</div>
<div class="background">
	<img class="full | portrait | landscape" src="imgURL" alt="" />
</div>

Background pattern or bullet without image file

Pretty sad that IE doesn’t allows you to use base64 encoding instead of real files. The best part is to use it for mobiles, since it saves you some http requests and precious time.
I’ve used it for a custom list style image without images. I just generated the base64 from Patternfy and pasted it in my CSS, like this:

	 ul {
		list-style-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAJCAYAAAAVb42gAAAAFklEQVQImWNgIAro56z9T4Ygbg5BAABTdwtkrDt7swAAAABJRU5ErkJggg==);
	 }

Text Shadow (IE included)

Again we will need some IE filters. But this time IE filters can destroy your font’s readability, so try not to use it too much and preferably, only when working with larger fonts.

	p {
		text-shadow: #000000 0 0 1px;
		zoom:1;
		filter: progid:DXImageTransform.Microsoft.Glow(Color=#000000,Strength=1);

		-ms-filter: "progid:DXImageTransform.Microsoft.dropshadow(OffX=-1, OffY=-1, Color=#000000)progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=-1, Color=#000000)progid:DXImageTransform.Microsoft.dropshadow(OffX=1, OffY=-1, Color=#000000)progid:DXImageTransform.Microsoft.dropshadow(OffX=1, OffY=0, Color=#000000)progid:DXImageTransform.Microsoft.dropshadow(OffX=1, OffY=1, Color=#000000)progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=1, Color=#000000)progid:DXImageTransform.Microsoft.dropshadow(OffX=-1, OffY=1, Color=#000000)progid:DXImageTransform.Microsoft.dropshadow(OffX=-1, OffY=0, Color=#000000)";
	}

Multiple borders (IE included)

When you want more than one border, for real browsers you’ll need to use an outline or :before and :after elements. For IE you could use filters to gain some an extra border.

	div {
		-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(color=#212121,direction=180,strength=0)"; /* IE 8 */
		filter: progid:DXImageTransform.Microsoft.Shadow(color=#212121,direction=180,strength=0); /* IE 7- */
	}
	div:before {
		position: absolute;
		top: 0px;
		width: 100%;
		height: 100%;
		border-top: 1px solid #212121; /* top border! */
		content: '';
	}
	div:after {
		position: absolute;
		width: 100%;
		height: 100%;
		top: 1px;
		border-bottom: 1px solid #212121; /* bottom border! */
		content: '';
	}

Box Shadows (IE included)

The same filter we’ve used to create a second border can be used to generate box shadows. Be aware that this filter can mess up an element’s width, so if you want to use it with any grid system, prepare for the headache.

	.shadow {
	    -moz-box-shadow: 0 0 4px #000;
		-webkit-box-shadow: 0 0 4px #000;
		-ms-filter: "progid:DXImageTransform.Microsoft.Glow(color=#666666,strength=3)";
		filter:
				progid:DXImageTransform.Microsoft.Shadow(color=#666666,direction=0,strength=3)
				progid:DXImageTransform.Microsoft.Shadow(color=#666666,direction=90,strength=3)
				progid:DXImageTransform.Microsoft.Shadow(color=#666666,direction=180,strength=3)
				progid:DXImageTransform.Microsoft.Shadow(color=#666666,direction=270,strength=3);
		box-shadow: 0 0 4px #000;
	}

Rounded corners

The bad part about almost-standard properties is that each browser implements its syntax differently. So for round corners we have a pretty strange behavior, where standards browsers have different ways to say same thing:

.rounded  {
	-moz-border-radius: 10px; /* gecko */
	-webkit-border-radius: 10px; /* webkit */
	border-radius: 10px; /* CSS3 standard */
	-khtml-border-radius: 10px; /* old konkeror */

	-webkit-border-bottom-right-radius: 10px;
	-webkit-border-bottom-left-radius: 10px;
	-webkit-border-top-right-radius: 10px;
	-webkit-border-top-left-radius: 10px;

	-khtml-border-radius-bottomright: 10px;
	-khtml-border-radius-bottomleft: 10px;
	-khtml-border-radius-topright: 10px;
	-khtml-border-radius-topleft: 10px;

	-moz-border-radius-bottomright: 10px;
	-moz-border-radius-bottomleft: 10px;
	-moz-border-radius-topright: 10px;
	-moz-border-radius-topleft: 10px;

	border-bottom-right-radius: 10px;
	border-bottom-left-radius: 10px;
	border-top-right-radius: 10px;
	border-top-left-radius: 10px;
 }

Screen reader only accessible content

Sometimes you want to improve the accessibility of your site, so you put some fancy links like “Jump to content” or “Jump to navigation”. So you just put “display: none” or “visibility: hidden” and hope it works, right? Well, it doesn’t. Some tests show that many screen readers just ignore the display:none or visibility: hidden part, so you don’t have any accessibility improvement.

What you can do instead is to use position absolute and hide this content above browsers visible area. But you have some risks on this technique, since it hides content, Google can consider it gray or black hat.

.hidden  {
	position: absolute;
	top: -10000px;
	left: -10000px;
 }

Don’t use negative text-indent

Since we’re talking about hidden content, take one more note, never use negative text-indent again. This is a known technique so you have a lot of SEO downsides by using it, since many bots can recognize it nowadays.
Just use alt attribute, that is much safer than hide content.

<h1><img src="myLogo" alt="My company" /></h1>

Clearfix (IE included)

Many of you know about .clearfix method for correcting heights when you use floats. Well, in many of these cases, that amount of code could be replaced by just two lines:

	.clearfix {
		zoom:1;
		overflow:hidden;
	}

@font-face (IE included)

If you’re still using cufon just because you don’t trust @font-face, think again.
Font Squirrel provides an amazing @font-face generator service, that allows you to put really good looking fonts in your site without worrying about all that JavaScript stuff.
The final code provided is something like this:

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

Pull quotes without image

We talked about this before, but it is possible to create curly quotes without any image. And it is not that hard. You just need a :before and blockquote:

	blockquote:before {
		display: block;
		float: left;
		margin: 10px 15px 0 0;
		font-size: 100px; /* let's make it a big quote! */
		content: open-quote; /* here we define our :before as a smart quote. It could be any content, even the HTML entity alternative to this opening quote, that is “ */
		color: #bababa;
		text-shadow: 0 1px 1px #909090;
	}

CSS for iPhone4 (higher resolution)

As time goes by we get more and more powerful mobile devices. It is a good practice to give create a mobile version, with reduced images and overall files size, but we have also to give a better experience for the ones with newer devices.
Since iPhone4 has a higher resolution, if you don’t provide a better (and larger) version of you logo, for example, your users will get a blurry version of it. This is a problem that can be solved with a very few lines:

@media handheld, only screen and (max-width: 767px) {
	.logo {
		/* common low-res and low-size, of course */
		background: url(logo.jpg) no-repeat;
	}
}

@media only screen and (-webkit-min-device-pixel-ratio: 2) {
	.logo {
		background: url(logo2x.jpg) no-repeat;
		background-size: 212px 303px;
	}
}

CSS landscape / portrait orientation for mobiles

This is a nice starting point for correcting layout bugs in each version of each layout mode for many mobiles, provided by stuffAndNoise

	/* Smartphones (portrait and landscape) ----------- */
	@media only screen
	and (min-device-width : 320px)
	and (max-device-width : 480px) {
		/* Styles */
	}

	/* Smartphones (landscape) ----------- */
	@media only screen
	and (min-width : 321px) {
		/* Styles */
	}

	/* Smartphones (portrait) ----------- */
	@media only screen
	and (max-width : 320px) {
		/* Styles */
	}

	/* iPads (portrait and landscape) ----------- */
	@media only screen
	and (min-device-width : 768px)
	and (max-device-width : 1024px) {
		/* Styles */
	}

	/* iPads (landscape) ----------- */
	@media only screen
	and (min-device-width : 768px)
	and (max-device-width : 1024px)
	and (orientation : landscape) {
		/* Styles */
	}

	/* iPads (portrait) ----------- */
	@media only screen
	and (min-device-width : 768px)
	and (max-device-width : 1024px)
	and (orientation : portrait) {
		/* Styles */
	}

	/* Desktops and laptops ----------- */
	@media only screen
	and (min-width : 1224px) {
		/* Styles */
	}

	/* Large screens ----------- */
	@media only screen
	and (min-width : 1824px) {
		/* Styles */
	}

	/* iPhone 4 ----------- */
	@media
	only screen and (-webkit-min-device-pixel-ratio : 1.5),
	only screen and (min-device-pixel-ratio : 1.5) {
		/* Styles */
	}

June 28 2011

10:00

CSS Counters – The Right Way to Organize Your Ordered Content

It is pretty common to see step-based content. Tutorials, shopping carts, FAQ’s, grandma’s recipes. You know, numbers and steps are really good to grab attention, so many writers use this.

But, talking about HTML how should we write it? Most (all?) use numbers as text in headings, as they were common content.

Well, let me tell you a secret: They are doing it wrong.

Actually we are doing it wrong ( nothing against this fantastic post of Ruben, just take a look at how we do the numbers, directly in HTML as text ).

A little time ago I was wondering about this thing, isn’t it more a CSS job? Actually yeah, it is. We have to keep content in HTML and presentation in CSS, and since we may want other ways to order titles, they are all about presentation. But, how can we do this kind of thing? One class for each item? That would be terrible!

Then CSS counter property comes to save us. It is a pretty unknown property that allows us to perform a simple count via CSS. It will be better explained with our demos :D

So, let’s rock!

Demo!

Take a look at what you will do at the end of this tutorial:


I think you should check out the demo, and download it to try out a little bit more!

So, counter?

Basically a counter is a “variable” that we can create with CSS but the only two possible operations that we can perform with it is to increase or to reset. For such operations we can use counter-reset or counter-increment CSS properties.

A basic usage is the first case mentioned in this post, the organized content. So let’s say you have a multi-step tutorial and want it organized automatically, what you have to do is just add this to your CSS:

body {
  counter-reset: first; /* our h1's counter is zero every time we have a body tag (hope only once) */
}
h1 {
  counter-increment: first; /* so, when we have one h1, our counter will increase one unit */
  counter-reset: second; /* and we will reset our h2's counter */
}
h1:before { /* wow, here we will append a pretty formated Step N - Item */
  content: "Step " counter(first) " - "; /* when you write counter(first) we will get its current value */
  font-size: 0.8em;
  font-weight: normal;
  font-style: italic;
  color: #bababa;
}
h2 {
  counter-increment: second; /* so our h2's counter goes up.. */
  counter-reset: third; /* and we reset the h3's */
}
h2:before {
  content: counter(first) "." counter(second) " - "; /* we will output H1NUMBER.H2NUMBER */
}
h3 {
  counter-increment: third; /* h3 goes up, up, up */
}
h3:before {
  content: counter(first) "." counter(second) "." counter(third) " - "; /* and we output H1.H2.H3 */
}

As you can see its usage is quite simple. Our downside is that we rely on content: property and after (or before) pseudo-element so older browsers won’t see this. But it should work just fine in IE8+ and other browsers.

Multiple counters

Another great thing is that you can have a “general” counter, you just have to separate multiple counters to increase with spaces. Just like this:

body {
  counter-reset: general first;
}
h1 {
  counter-increment: general first;
  counter-reset: second;
}
h2 {
  counter-increment: general second;
  counter-reset: third;
}
h3 {
  counter-increment: general third;
}

Better Ordered lists

Using almost the same code, you can create better ordered lists, with sub-items control.  So instead of just 1 – ITEM you can have 2.5.3.1 – ITEM when you have multiple nested OL’s. This is the code I’d use:

ol {
	list-style: none;
	counter-reset: olfirst; /* our father OL must have olfirst item reseted */
	font-family: arial;
}
ol ol {
  counter-reset: olsecond; /* our sub OL's reset the olsecond, third must to be olthird and so on */
}
	ol li {
		counter-increment: olfirst; /* when we have a item that is children of first OL, it increases first counter*/
	}
	ol li ol li {
		counter-increment: olsecond; /* when the item is children of a OL that is children of another OL, so it is a sub OL */
	}
	ol li:before {
		content: counter(olfirst) " - "; /* let's output our pretty number */
	}
	ol li ol li:before {
		content: counter(olfirst) "." counter(olsecond) " - "; /* let's output our "sub-number" */
	}

Are you hungry yet?

This is a pretty tricky attribute so you must to try it out a couple of times until you are familiar with it. But we have some tutorials at W3Schools about CSS counter reset, CSS counter increment and beforeafter pseudo elements that can help you a lot.

So, it is time for you to talk. Did you know about this property What do you think about it?

June 27 2011

10:00

An Introduction to Object Oriented CSS

With richer interactions and media heavy pages mushrooming on the web, creating web pages, which load faster and respond well has become a challenge. Separating the content, presentation and behavior of a page using HTML, CSS and JS, is not the only thing that front-end engineers have to concentrate on nowadays. The limelight is now on the performance of the pages, cleanliness and leanness of the code within, scalability and reusability of CSS, and the semantic correctness of the markup.

There are a handful of frameworks, techniques and approaches that are built towards this goal of maintainability, scalability and reusability of CSS. Each of them is having its own pros and cons. But, this is not a stage to elaborate on all of them.

This article is an introduction to implementing the concept of ‘Object Oriented Programming’ in building CSS for high scale websites and applications, with an eye on maintainability and reusability.

What is OO CSS?

The concept of ‘Object Oriented Programming’, is widespread among developers, and forms the basic for any modern programming language. Features like data abstraction, modularity and inheritance make it a favorite in coding large-scale applications.

Object Oriented CSS, as the name suggests, is implementing the concepts of OOP in structuring and building CSS rules, which are easy to reuse, thereby reducing the loading time and increasing the performance of web pages incredibly! The key point here is, to identify, build and style modular reusable ‘objects’ in a page, and to reuse it in multiple instances by extending them with additional features wherever needed. Here an ‘object’ refers to the basic HTML markup and its CSS rules. Apparently, here, the key challenge is going to be, identifying the ‘object’ and building rules for it.

This is neither a framework nor a technology, but an approach adopted in building the rules, so as to make the code more reusable, maintainable and scalable. You may already have been making use of this concept in coding your style-sheet for years, but may not be aware of this terminology :).

A UI engineer at Yahoo (‘Nicole Sullivan’ ) coined the term. She had made a number of presentations on the topic on various big stages (http://developer.yahoo.net/blogs/theater/archives/2009/03/website_and_webapp_performance.html) and is also included in a feature on Women in Technology.

Nicole, who has been hired by Facebook recently, for optimizing the CSS and web page performance, has been leading the way in implementing this approach in the pages for the social networking giant, and the results are to be seen. A faster loading FB, with significantly less response time! This is exactly what this approach of building CSS promises to give back. But again, like all other frameworks, this too has pitfalls and advantages which we shall discuss in detail.

Following are some key aspects in object-oriented approach to CSS building:

  1. Create a component library
  2. Separate container and content / Avoid Location dependent styles
  3. Separate Structure and skin
  4. Extend base objects using class names
  5. Stick to semantic class names

Create a component library

This is the first thing to do, while building a OO CSS framework for your application, and this is the most time consuming process too. You will have to carefully study the screens of the app, and come up with the recurring reusable UI patterns, and will have to create a library consisting of HTML markup and respective CSS rules of all such components first. This may take some initial time, as you may need to filter out the components and find out the basic structure of a component, and its variations along different screens.

E.g. For a blog, ‘metadata (Refer to the marked area in the figure below)’ will be present in multiple instances of a page. After closer scrutiny, you will come to know that, all the metadata can have the same HTML markup, and the variations can be addressed using CSS (the font size, color, margin and padding are different in each of the occurrences of metadata component). Select a markup, as a base structure, in which you can accommodate majority of the elements that possibly can come in the particular component.

In our example our basic structure of the ‘metadata’ component will be:

Base Markup


<p class=”metadata”><a>Author name</a>commented on<a>21-02-2010</a>@</p>

Base rule


.metadata{font-size:1.2em; text-align:left; margin:10px 0;}

Thus, ‘metadata’ can be now independently used within any other element in the markup, and will have a consistent look and feel, irrespective of where it is used. But as we can see in the figure above, there are multiple variations of the component. This we will tackle using CSS, and will be discussing in the following points.

This way, figure out all the reusable components, and create rules and markup, and group them separately in the CSS file. (It’s even fine to create a separate CSS for the component library, and then merge it with others later during deployment.)

Separate Content from Container / Avoid location dependent styles

This is one of the primary requirements of following an OO approach to building CSS files. The core idea here is to consciously differentiate the rules of containers and the content that comes within them, so that content can be plugged into any containers irrespective of their parents.

Often while building large-scale CSS rules there will be instances where a single component will be appearing differently in various instances, when put in different containers. One of the solutions adopted by front-end engineers, for addressing this problem was to assign location dependent selectors to that particular component.

E.g. With reference to the example used in the previous point, where there are multiple variations of the same component – ‘metadata’, each instance can be given location dependent rules by combining the base class ‘metadata’ with the relevant classes/IDs for the containers. i.e.,

‘metadata’ in a blog post can be styled as: .post .metadata{overriding rules}
‘metadata’ in a comment can be styled as: .comment .metadata{overriding rules}
‘metadata’ in a comment can be styled as: .comment .metadata{overriding rules}

The OOCSS approach advocates avoiding this type of usage. Instead extend the base class by adding more classes, thereby extending the attributes of the base component to match the variation. We shall discuss the concept of extending the base class in the following points.

Separate structure and skin

In the first point ‘Creating component library’, we discussed the importance of identifying reusable components, and building base classes and base structures for them. While creating those base rules, an important thing to keep in mind is to separate the structure and skin. In other words, while defining a base class in the component library, we should not create skin-level rules, like width, height, background images, border styles, etc, that can make the component more specific to a certain container.

E.g. For our base class, ‘metadata’ with the following rule

.metadata{font-size:1.2em; margin:10px 0;},

Adding more skin-level rules as below,


.metadata{font-size:1.2em; margin:10px 0; <strong>width:500px; background-color:#efefef; color:#fff;</strong>},

can make it more of a specific component than a generic one, thereby making it difficult to reuse it in many other containers, which would need it to be rendered in a different ‘skin’. Also another danger of not separating structure and skin will be the ‘Specificity war’.

Extend base objects using class names

As discussed in the second point ‘Separate content from container’, avoiding the usage of contextual selectors will make the content independent from their parent containers and hence will be truly usable across the application. So how do we instantiate the variations of the same object in different containers? What is the solution? Well here comes the concept of extending the base ‘object’ (again another term coined by Nicole Sullivan), by adding more class names to it depending on the context, rather than tightly coupling the object with the class names of the containers in which it is to be placed.

E.g. In the first figure of the ‘metadata’ object, where the same object needs to be rendered differently in various containers,

The HTML markup of each of them will look like:

<p class=”metadata commentmetadata”><a>Authorname</a>commented on<a>21-02-2010</a>@</p>
<p class=”metadata postmetadata”><a>Authorname</a>commented on<a>21-02-2010</a>@</p>
<p class=”metadata authorlistmetadata”><a>Authorname</a>commented on<a>21-02-2010</a>@</p>

The CSS rules will be:


.metadata{font-size:1.2em; margin:10px 0;}
.commentmetadata{font-size:1em; margin:0 0 10px 0; color:#063070; }
.postmetadata{ color:#063070; }
.authormetadata{ color:#fff; }

This is a very simple demonstration, to comprehend the concept of implementing OO programming. As the size of the app becomes larger, the UI patterns will become more complex, and there lies the actual challenge and advantage of using such an approach.

Stick to semantic class names

A challenge in building CSS for high-scale web applications is to logically come up with meaningful class / ID names matching with the context and moreover making sure, they are reusable and still make sense. With the concept of ‘extending’ base objects, it’s easy to fall into the practice of creating ‘presentational class names’. Some easy examples are ‘leftCol’, ‘redText’, ‘midCol’, ‘bigText’, ‘bolderText’ etc. Such class names are not reusable and are a hindrance to scalability.

Always stick to logical and semantic class names relating to the logical meaning of the component, rather than its presentational meaning. It means, instead of giving the text block with a yellow background color, the class name ‘yellowText’, ‘notification’ would be a more sensible name, as it is a notification element that pops out to notify some activities within the system.

Pros and Cons?

Following such an approach of building CSS has its own pitfalls and advantages

Here are a few cases, where adopting such a framework ‘may’ backfire:

  1. OOCSS is suited to really large websites / application which are filled with reusable components. It may not give desired results in smaller websites and applications. So decide sensibly depending on the size of the work in hand
  2. If not smartly used, creating the component library can turn out to be a mess, and become a maintenance nightmare for other coders
  3. Documentation is a must. Each block of code should be clearly commented out with the right points for other coders to absorb the concept, which otherwise can become too tedious in case of a knowledge transition

Some obvious advantages of adopting this approach are:

  1. Less lines of CSS code
  2. Cleaner HTML markup, with logically sensible class names and hierarchy
  3. Semantic markup, means more SEO friendly pages
  4. Far better page optimization, with much faster loading times, since most of the components are reused
  5. Scalable markup and CSS code, where more components can be added into the library without disturbing other components, as the base objects are independent of any other containers
  6. Easily theme-able layouts, since changes to the base object can completely change almost the whole presentation layer instantly

Courtesy & Resources

http://www.webdirections.org/blog/object-oriented-css-the-video/

http://www.stubbornella.org/content/2009/02/28/object-oriented-css-grids-on-github/

http://www.iconfinder.com for all the icon resources

June 20 2011

07:00

10 HTML Entity Crimes You Really Shouldn’t Commit

It has been over a couple of years since I posted my HTML tag and usability crimes posts, both of which are amongst the most popular articles here on Line25. There’s something about this title people just can’t resist! Let’s take a look at ten crimes you may be committing in your HTML content. These won’t exactly land you a life sentence, but I bet almost every one of us will be guilty of at least one of these petty crimes.

Crime 1: Not converting your ampersands

Ampersand

One of the most common HTML validation errors I see when checking the code behind Sites of the Week features are unconverted ampersand characters. It’s easy to simply paste in your content from an external document and forget to transform your & characters into the correct &amp; HTML entity.

Crime 2: Making your own ellipsis

Ellipsis

Did you know those three dots used to indicate a pause in a sentence are called an ‘ellipsis’? Rather than typing three periods or full stops it actually has it’s own glyph as the &hellip; HTML entity. The spacing between the dots in the entity is much tighter than the standard spacing between three full stops or periods. Remember, there’s only ever three dots (four in certain situations), don’t be the person who extends their ellipsis to 6+ dots………..

Crime 3: Incorrect use of the em dash

Em dash

I’m definitely guilty of this one myself. I can never remember when to use Em dashes over En dashes, and what’s worse I tend to stick in a plain old hyphen which makes the crime even more serious! The Em dash or &mdash; in HTML entity format is typically used to separate a break of thought in a sentence.

Crime 4: Incorrect use of the en dash

En dash

Similar to the Em dash crime, the En dash is another form of dash often misused in our body copy. The En dash or &ndash; in its HTML entity form is used to express a range of values or a distance, so essentially the En dash is placed where you would say the word “to” when talking about age ranges or a journey between two places.

Crime 5: DIY Copyright symbol

Copyright symbol

I’m sure we’re all familiar with the international copyright symbol—the letter C with a circle around it ©. Rather than use this standardised symbol, sometimes people decide to construct their own with brackets, (c), probably because they couldn’t figure out the keyboard combination to insert the symbol in Word. Thankfully it’s much easier for web designers with the easy to remember HTML entity of &copy;.

Crime 6: DIY Trademark symbols

Trademark symbol

Similar to the copyright symbol, the trademark symbol has its own HTML entity glyph as &trade;, so there’s no need to design your own from styled <sup> or <span> tags.

Crime 7: Plain text fractions

Half fraction

Another common addition to every day body text is the use of fractions to show quarter, half or three quarters in their shorthand, numeric format. I’m sure we’re all guilty of writing 1/4, 1/2 or 3/4 as opposed to their HTML entity counterparts of ¼, ½ & ¾ as &frac14;, &frac12; & &frac34;.

Crime 8: Plain text mathematics symbols

Divide symbol

Common mathematical symbols such as add, minus, multiply and divide are also misused in general body text. The add and minus symbols not so much, as they’re easily created with their designated keyboard buttons, but multiply and divide are usually seen as the letter x, an asterisk *, or a slash /. × and ÷ symbols can be easily created with the HTML entities of &times; and &divide;.

Crime 9: Supersized degree symbols

Degree symbol

The degree symbol is not the most common glyph used in every day body text, but it’s necessary when talking about temperature, angles or longitude/latitude map locations. We often see the degree format in disguise as a plain old letter o, but it can be created correctly using the &deg; HTML entity like so: 45°.

Crime 10: Somewhat straight curly quotes

Curly quotes

A massive pet peeve for many, the incorrect use of quotes in textual content is one of the most common typographic errors on earth. The standard quotation marks entered with our keyboards are the numerical type which indicate a unit of measurement such as 5′10″. When quoting people, curly quotes should be used with the &ldquo; and &rdquo; entities: “Now I, Skeletor, am master of the universe”, or for single quotes the &lsquo; and &rsquo; entities.

HTML Entity names vs entity number

Every HTML entity can be written as its name value &copy; or as its numerical value &169;. The main advantage of using an entity name is the character is easily recognisable as the name often relates to the actual entity in question (copy = copyright). However entity names aren’t as well supported as entity numbers, which have good all round support.

June 13 2011

10:00

10 Tips to Boost Your HTML Forms Performance

Sometimes we get so used to doing things one way that we forget a little and important thing: to improve. We get so involved with all this CTA stuff that we forget other important things, like the contact form that comes after the pretty button.

Our task today is to improve our form, to get better conversion rates, and maybe learn something from it.

We will be talking about conversion, code, and design, in an easy and practical way.

So, let’s stop talking and rock some forms.

1. Test and track everything

Before changing anything, you need to learn how to do split tests so you can measure your improvement. Since there is no magic formula, some techniques that work for other people just don’t work for you and vice-versa. It’s kind of a trial and error process.

We have a lot of tools for this tracking job, including tracking goals and funnels with Google analytics or recording users interactions with Clicktale.

2. Increase conversion by 25%~40% with “Mad Libs”

According to Wikipedia:

Mad Libs consist of a book that has a short story on each page with many key words replaced with blanks.[...] One player asks the other players, in turn, to contribute some word for the specified type for each blank, but without revealing the context for that word. Finally, the completed story is read aloud.

It sounds funny, isn’t it? Well, it is also really good for business. LukeW wrote an article about how 2 guys (each one in his own site) have increased dramatically the conversion rates, with this technique.

We have a lot of examples that when you turn your software more friendly, you get much better results. So when you do not have a simple form, but a dialogue the user seems more open to fill it.

3. Captchas are bad guys

Unless you are a nice guy and want to help in the book digitizing business, I recommend you to remove your captchas.

I say this because we have some alternatives that are almost as efficient as captchas are, but without the downside of reducing our conversion rates.

We have two good examples, one guy who increased his conversion by 33% and other that lost 3.2% of his conversion while captcha was active, because some people couldn’t complete the process.

Both replaced captcha with honey pot fields and just kept spam at a low level.

4. Don’t put optional fields

This one is really simple. If this information will be used, you need an obligatory field. If it isn’t you don’t need this field.

If you really want to get more information about your users, I recommend you to ask for it after they have finished their current activity (buying, registering…) so you don’t waste their time with not-so-important things and keep your forms as short as possible (you know, long forms are bad, bad guys).

5. Use steps in checkout pages (avoid one page checkout)

Actually I’ve done this one wrong many times. When users see long forms they just don’t want to spend their time filling it out. But the funny part is that if you break a long form in 3 little forms, they are much more open to complete the process.

Proimpact 7 gives us 5 reasons why not to use one page checkout. Basically, it is because they can reduce your conversion rate by 60%.

6. Remove that reset button

All reset buttons should have the label “you’ve been rick rolled”. Really, 99,999% of the cases you just don’t need them, and it can make the user lose all his data. Jakob Nielsen is pretty extremist about it, he says “Reset: Don’t use“.

7. Don’t mask passwords

This is a pretty controversial thing. Sometimes it is better to mask sometimes not.

What you have to keep in mind is that sometimes it’s good to give the users the options to “unmask” the password field.

Jakob Nielsen again has a pretty extremist opinion that you must stop password masking. I don’t think it really works  this way, but you can try this alternative and measure your results. :D

8. Validate fields

Sure, you must be clear about how users must fill some form fields, but it is impossible to prevent all errors. So it is good to have some client-side form validation, like Vanadium, so users can see what is wrong while they are still typing.

9. Label above the field is better

Above is an eye tracking study that shows how users find it much easier to relate the labels to the fields while they are above them.

It is a really good study of UXMatters about label placement in forms. The only downside of labels above fields is that they need more space so the form can look bigger while it has the same number of inputs than others.

Another good alternative is sliding labels, but I think that has potential to save space and be easy to understand.

10. Auto complete is your friend

Don’t know why aren’t you using it yet.

Don’t be afraid to use some custom elements

Sometimes we need calendars, multiple selects, sliders and others elements that aren’t available in HTML or they are really bad by default.

When you have this, don’t be afraid to use jQuery enhancements to your form (non-obtrusive way, of course). We have a lot of plugins and resources to help us in this task.

One really good example is Uniform, that creates sexy forms with jQuery. It’s really worth 5 minutes of your attention.

Are you hungry yet?

I’m sure you have read something about it too. Why don’t you join this conversation and put you thoughts in comments?

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 ...