How to Improve Website Performance Using CSS Sprites

CSS Sprites is a technique by which we can combine multiple images in a single big image and position the various parts of this big image with our elements using pure CSS attributes. The primary objective behind using CSS Sprites is to decrease the number of HTTP requests and thus decreasing the request stress on server. The idea behind CSS Sprites is to consolidate multiple images into one sprite and then selectively display portions of this sprite with positioning. It starts by creating a larger CSS Sprite by grouping more than one images (usually icons) together and aligning them in proper grid style to aid the positioning. Then it is aligning used a proper positioning values on the webpages to show their respective images. This way it decreases the number of HTTP requests and thus increases the overall speed of webpages.

Sometimes back, we used the favourite slicing technique to break down a larger image into smaller slices (parts) so as to make pages load faster, but all this technique was only fooling our eyes as the page looked like loading faster, while in reality it was not. Each of those images was fed up as a separate request to the server and would increase the time of loading actually.

According to Yahoo UI blog, the resultant sprite created by joining smaller images is always smaller in size than the combined contributed parts. It is because we have to use a single color table for the sprite instead of individual color tables for the contributed ones. Another advantage of using sprites is that this way we save the overhead required by the images.

Reduce File Overhead using CSS Sprites

Imagine a site that has 10 sliced buttons for the main navigation and each button has an accompanying graphic for the hover state. A total of 20 files would have to be downloaded just for the navigation. That’s 19 files of unnecessary file overhead.

If there were 10,000 fresh visits to the web site 200,000 downloads would potentially occur. I say potentially because depending on how the web page was created the hover state buttons may require a “hover” to occur before they are downloaded. Either way at least 100,000 downloads would be required, reducing the number of available connections to the server and littering the pipe with unnecessary file overhead.

If a CSS Sprite were used only 10,000 downloads would be required and considerably less bandwidth would’ve been used, allowing the site to make the most of the bandwidth allotted by their hosting provider.

Reduce Connection Overhead using CSS Sprites

When you visit a web site an HTTP connection is established between you and the web server. Once connected, your web browser requests the document you asked for (an HTML home page, perhaps) and after receiving the file it is read to determine what else needs to be downloaded and how to visually render the page.

How CSS Sprites Help in Connection Overhead

Notice in the CSS below how the anchor tag does not get a background-image, but each individual class does.

css-sprites-example

Using CSS Sprites, we can really lighten this example up. Instead of having ten separate images for the buttons (five default states and five rollover states), we can literally combine all of them into one big long image. I won’t go into great detail about how this is done, I’ll just give you a basic walkthrough. Create a new image that is as wide as your widest image and and as tall as the combined height of all your images plus X pixels, where X is the number of images you have. Now place you images into this new image, left aligned, one on top of the other with one pixel of white space in between.

css-sprites-example-2

We were able to reduce the number of HTTP-Requests by 9 and the total file size of the image(s) by 6.5 KB. That’s a pretty huge improvement for such a little example. Imagine what you could do on a full website.

Benefits and pitfalls

A couple of final thoughts. Our new CSS Sprite method tests well in most modern browsers. The notable exception is Opera 6, which doesn’t apply a background image on link hover states. Why, we’re not sure, but it means that our hovers don’t work. The links still do, and if they’ve been labeled properly, the net result will be a static, but usable image map in Opera 6. We’re willing to live with that, especially now that Opera 7 has been around for a while.

The other concern is familiar to anyone who has spent time with FIR. In the rare cases in which users have turned off images in their browsers but retained CSS, a big empty hole will appear in the page where we expect our images to be placed. The links are still there and clickable, but nothing visually appears. At press time, there was no known way around this.

Then there’s file size. The natural tendency is to assume that a full double-sized image must be heavier than a similar set of sliced images, since the overall image area will usually be larger. All image formats have a certain amount of overhead though (which is why a 1px by 1px white GIF saves to around 50 bytes), and the more slices you have, the more quickly that overhead adds up. Plus, one master image requires only a single color table when using a GIF, but each slice would need its own. Preliminary tests suggest that all this indicates smaller total file sizes for CSS Sprites, or at the very least not appreciably larger sizes.

And lastly, let’s not forget that our markup is nice and clean, with all the advantages that go along with that. HTML lists degrade wonderfully, and a proper image replacement technique will leave the text links accessible to screenreaders. Replacing the sprite imagery is dead simple, since all of our dimensions and offsets are controlled in a single CSS file, and all of our imagery sits in a single image.

CSS Sprites can save you from connection overhead, though its quite a task but if done carefuly will do wonders. Reducing the number of HTTP requests has the biggest impact on reducing response time and is often the easiest performance improvement to make. I would love to hear your comments. Subscribe for our RSS for free updates delivered to you.

How Your HTML Becomes Garbage HTML?

Garbage HTML: Impact and Causes

Developers around the world are writing HTML pages and they try to be as specific as they can in terms of cross browser issues but when it comes to standards they usually ignore them. We can term such HTML pages created by them as wasteful HTML. These pages cost you in terms of bandwidth, load times and sometimes HTML rendering time. If you look at the source code you will notice that there are white-space which is almost 3 times of the actual HTML code which is useless and measured in KB. You may think that the white-space is left for indentation purposes but its not the case, these white-space is left due to ignorance. Removing those extra white-space can sometimes reduce the page weight up-to 50%.

Moreover, Instead of defining two cell classes in an external style sheet which gets downloaded once as cached, and using the right class in the tag, the HTML writers sometimes use an inline style attribute on every row tag. Same is with JavaScript which could and should be stored in an external file.

These ignorance or mistakes whatever you call it not only make your HTML or templates more difficult to maintain, but all of the inline JavaScript and CSS styling discourages reuse, standardization, and other good habits. It also makes a site significantly harder to maintain.

Characteristics of Garbage HTML

Garbage HTML has a special something to it, a unique blend of being not just invalid, but disgustingly so by going beyond minor misunderstandings or typos and far into the realm of negligence — improperly nested tags, tags that are never properly ended, incorrect attribute usage, and so on.

Why Developers Can’t figure out Garbage HTML themselves

  • Ignorance: A large number of developers don’t know HTML properly, sometimes they aren’t keen but sometimes they aren’t taught well. Many developers starts learning HTML by copying and pasting code from some other source which may or may not be perfect. Usually if the page is looking properly they don’t even care what is written in the background (HTML code)
  • Poor tools: Tools used by the developers to produce HTML, whether its some sort of HTML WYSIWYG editor or maybe a framework/library that is generating bad code. There are reasons why some of these tools can’t generate code. For example, until recently, those on-screen, web-based HTML editors had a much easier time rendering the font tag than a CSS class or even an inline style. The end result? HTML widgets that were generating the font tag for HTML nearly 10 years after font had become deprecated. Another problem is that there is not a 1:1 mapping of stylistic effects and the way to make the effects happen. Without editors that are strictly contextual driven, there is no good way for the tool to know that [Ctrl]I should result in the em tag as opposed to a CSS style that makes something italic.
  • HTML is too semantic: HTML is transitioned to being as purely semantic as possible without completely breaking backwards compatibility. In general, this is a good thing. But for a developer who is trying to finish their work and go home, it is a nightmare. Which tag does the developer use? What if the developer wants the effect that a tag produces, without the meaning of the tag? It’s enough to drive anyone insane. So what happens? Developers stop caring about what the HTML “means” and just do enough to make the page render the way the client wants it to look. In the shuffle, the HTML ends up being a mess.
  • Developers who never updated their HTML skill sets: HTML is evolving unlike any other languages but developers haven’t updated their skill or learned recent tags, tricks or syntaxes. Maybe they learned HTML in 1997, or the book they bought on the bargain bin in 2002 was from 1997. Who knows? But their HTML is stuck in the HTML 3 years, and they haven’t updated it since.
  • Server-side technologies: Many developers are concatenating strings which is HTML and they print as per logic. This is where the problem lies, as there is no way to visualize the HTML output beforehand. That is a sure way to not be able to get the code right. e.g.

  • Work & Deadline Pressure: Generally the deadline involved with the HTML projects doesn’t give enough time to validate the HTML properly. Client generally thinks that HTML projects should not take much time and they don’t care about proper HTML. They are happy as long as they see their desired output. Situation becomes worse when they are notified about HTML issues by their expert friend. They come back yelling, without considering that they haven’t given enough time to validate HTML properly.

Any Solution to Garbage HTML Problem

I think some parts of this problem are not likely to be corrected. Most developers who care about doing things right are using tools that combine just enough visualization to make life a bit easier, without completely taking over the process. Some developers may be running their code through validators or keeping current on what is correct and what isn’t. But at the end of the day, there is no way to force a developer to start caring about these things unless you are their boss. After all, browsers will display even the worst HTML code, as long as it somewhat makes sense.

In my experience, only about 20% of developers really understand how to accomplish something as well as why they should do it that way and what the consequences are. That’s the same 20% or so who are probably writing decent HTML.

If you’ve got any thoughts, comments or suggestions for things we could add, leave a comment! Also please Subscribe to our RSS for latest tips, tricks and examples on cutting edge stuff.

Creating Image Map using CSS

Image Map is used to present your pictures in much user friendly nature. They are great to present something to end users. Though, the rise of Flash has decreased the use of Image Maps but still there are places where you can use it.Image Map is basically an elaborate variation of the <a> tag, an image map allowed an image file to contain multiple hotspots that linked to any number of web pages or external sites. CSS does allow you to create an image map with some subtle mouse over effects with a few slick modifications to the <ul> and <li> tags.For this exercise, we’re going to use the image shown below to create an image map with two hotspots using CSS code. Save the file to your hard drive and then open it in an image editor that will allow you to measure the image in pixels.

This image will be used to create a CSS image map

Now that you have the image saved to your hard drive and open in an image editor, let’s start coding the HTML and CSS code that will make the image map. In a text or HTML editor, enter the code below, then save your file with an .htm extension.

You can see that by the content of the body of the HTML code that we will be using CSS to style a bullet list (ie, <ul> and <li> tags) in order to make the hotspots for our image map. In fact, if you were to preview the document in a browser right now, all you would see is a bullet list.

Let’s start writing the CSS code and creating a style ID called “photo”. Begin by entering the code into the <head> of the document that you see in the code below.

Note in line five of the code that the CSS style is denoted with a hash mark, or pound sign (#), at the beginning of the photo style. This tells the browser that the style is an ID type and not a Class type, which is denoted with a period (.). CSS IDs are preferable to Classes in many cases, because if an HTML element is wrapped with a <div> tag that is defined as an ID, rather than as a Class. We can define how other HTML tags within that <div id> will be displayed and no further mark-up to the HTML within that <div id> tag will be needed.

You can also see in line nine of the code that we are using the downloaded image above as a background image. This is because both Internet Explorer 6 and 7 have issues displaying the <ul> and <li> elements over an image that is placed with an <img> tag. Be sure that the path to the image fruity_cones.jpg on your hard drive is accurately coded in relationship to the .htm document that you’re building.

Now that the #photo ID has been established, let’s code the cascading elements that will appear within the ID. Enter the new code that you see below.

By defining any <ul> tag that is wrapped within the #photo ID as having a list-style of none, we are stripping the display of any type of bullet points.

Continuing on, let’s code how the <a> tag will appear within the #photo ID. Enter the code below.

When defining the <a> tag style within the #photo ID, it is important that the position: absolute; attribute is present, because it tells the browser to constrain them to the top-left corner of the photo. Otherwise, the hotspots in the final image map would be off by however many pixels the browser is going to use to float the background image.

The width and height define the size of the clickable hotspots on the image map, while the vital attribute text-indent: -1000em; tells the browser to display the hotlinked copy within the <li> tags way, way, to the left of the browser window so that they will never be displayed over the background image.

We’ve also defined an a:hover class within the #photo ID, so that when the user’s mouse cursor hovers over a hotspot on the image map, a white box will appear.

The last bit of coding is the trickiest. Go to your image editor, where the image you downloaded should still be open. Measure, in pixels, how far from the top and the left edges of the image you should place the hotspots for your links. In this example, we’re going to link to two external websites. One will be linked by clicking on the apple, the other by clicking on the orange.

Therefore, we need to define two new classes of the <a> tag, which will be wrapped in the <div id=”photo”> tag. We’ll call them apple and orange. These classes will also dictate the location of the links on the background image. Add the new code that you see below.

And with that, our CSS image map is complete. Save the document and preview it in your browser. You’ll see that the title attributes in the <a> tags of the document give us a nice label, ala the <alt> tag.

The final CSS Image map, with mouseover effects

While Image maps are still considered valid HTML, you can use this CSS method to finally separate content from presentation. It also has the advantage of using less code for more complex image maps, and is good practice for knowing when to declare IDs rather than Classes in your CSS code.

If you’ve got any thoughts, comments or suggestions for things we could add, leave a comment! Also please Subscribe to our RSS for latest tips, tricks and examples on cutting edge stuff.

Five HTML odds you might haven’t encountered yet

You may be writing HTML since many years but here are five Odd things about HTML which you might haven’t encountered yet. These Odds are surprising but real.

<DOCTYPE> does not matter

I know… this one is shocking. After all, doesn’t the validator use the <DOCTYPE> to determine which rules to validate the document? Yes, it does. The implication of this is that the browser does the same; it looks at the <DOCTYPE> and makes a determination based upon it regarding which parsing rules, presentation mechanics, etc. are applied to the document. The reality is, the browser completely ignores <DOCTYPE>! If you are using XHTML, this may be a different story because XHTML is more rigid, but I would not be surprised if this were not the case. If you have been using <DOCTYPE>, and you’re hoping to trigger a browser to do certain things based on it, don’t bother. What happens instead is that the browser has its built-in HTML rules, and it applies the rules to all documents, regardless of <DOCTYPE>.

Browsers are much more compliant than you think

One of the persistent complaints about various Web browsers (usually Internet Explorer) is that, because they are not fully compliant with the HTML spec, they render things very differently. The reality is, browsers are much more compliant with the HTML spec than you think. And those obnoxious variances in rendering? The HTML spec is generally silent as to how things should render in a Web browser. There are some “should” and some “should not” items regarding rendering in the spec. But chances are, if one browser doesn’t do what you expect it to, if you check the HTML spec, it is probably silent on the matter. Those differences in error handling and how invalid HTML is dealt with? Again, the current HTML spec is pretty quiet about those things. Blame HTML 4, not the browser. Luckily, HTML 5 is much more specific on these points, which should alleviate much of the differences between browsers.

Compliance does less than you think

The other side of the compliancy coin is that a browser’s compliance with the HTML specification is little guarantee that your document will display the way you expect it to. Because so much of the current HTML specification is worded with “should” and some “should not” (as opposed to “must”  and “must not”), browser vendors have a lot of leeway in how things are done, while still remaining compliant with the spec. Again, HTML 5 is working hard to make these things more clear and to reduce these kinds of issues.

Validators cannot cover all of the bases

Another favorite tool of many Web developers is the trusty HTML validator. What many programmers don’t realize is that aspects of the specification are not machine verifiable! In most cases, the validators can work, but in some they cannot. There are a number of instances in the specifications where whether something is allowed is based on circumstances that a computer just is not well suited to detecting. So, yes, keep using your validator, but be sure to check your code against the specification too when possible.

The <q> tag

The <q> tag is supposed to be used for an inline block of text that represents quotes. An analogy is: “<blockquote> is to <div> as <q> is to <span>.” For a number of reasons, <q> is not widely used. When quotations are marked up with HTML, it is usually with the much more popular <blockquote> tag. So what is so strange about <q>? As a tag, it is supposed to do something that no other tag does: It is supposed to automatically surround its contents with quotation marks. This behavior is not well specified in HTML 4, and Internet Explorer never implemented it. As a result, authors who used <q> have traditionally put in browser detection to add the quotation marks in Internet Explorer. In Internet Explorer 8, its behavior will be updated to comply with the spec as well. While this is good overall, it will break the code with browser detection. While the idea of a tag adding punctuation may be unusual (as far as I know, <q> is the only tag that does it), the authors currently using <q> know enough to expect it.

Leave me a comment and let me hear your opinion. If you’ve got any thoughts, comments or suggestions for things we could add, leave a comment! Also please Subscribe to our RSS for latest tips, tricks and examples on cutting edge stuff.

New Heights for web applications

When it comes to programming, more specifically the development of web applications, it is important to consider all the tools of the trade before using the one that is going to be used for the job.

PHP is great. With the release at the time of PHP 4 and now its time for PHP 6. it’’s initial object functionality I started to get up to speed with many of the OOP principles. I was building some pretty amazing Content Management Systems, Digital Asset Management Systems, even Web Top Publishing Systems. My previous commitment to learn Java was fading as my experience grew with PHP was growing, seeing that I could build all the amazing things with what I had originally felt was a subordinate language.

We have search the performance for the PHP and many other languages like python,Perl,java,Vb,and finally ruby, below the difference between all the programming languages as graph which shows the future for the PHP.

Following graph shows the new lines of code in various languages in recent years

Newlinesofcode

PHP dominates the new lines of code and only PHP and Ruby are on a steady curve upward.  Yeah – I know that “number of lines of code” is not a great measure, but none of these languages are overly verbose so it’s an interesting proxy metric.

Activedevs

Active developers tells a different story.  While PHP is growing a little relative to the others, they all seem to have a relatively flat curve.  The well known shortage of Ruby developers is reinforced by this data, as well as the next graph.

Newprojects

Comparison between all the programing language..

Does it prove anything?

This was the chart I found really interesting.  Ruby is clearly the trendy new language.  Given normal supply / demand lags, you’d expect that this is a leading indicator of a significant uptick for Ruby on the other two charts in 2007.  My conclusion is different than Robin’s – while PHP appears to be dominant today, the rapid growth in new projects in Ruby indicates that it is currently positioned as “the language of the next wave of applications.”  This is consistent with what I’m hearing and seeing from many new startups.

Conclusion

I suspect very few people will argue that PHP is a more elegant language or is more powerful than Ruby. Frankly, Ruby is probably may favorite language that I have ever worked with and I have worked with Classic ASP, ASP.NET, VB.NET, C#, Java, and Perl all rather extensively over the years. Ruby is both highly expressive and concise which is rare and refreshing.

Rails is a very comprehensive and effective web development Framework and there’s nothing exactly like it in PHP. You get a huge amount of functionality for free. Developing in Ruby on Rails is also a very fast process because Ruby is a very concise language requiring much less typing than any other language I’ve worked with. Code Igniter is a really nice PHP framework. It will give you a great boost when developing your next PHP application.

The hosting and deployment struggles with Ruby on Rails is a major sticking point for me though. As the owner of a web development company many of our smaller clients do not have the budget for their own VPS account and even if they did, we don’t have the staff to manage a large number of VPS accounts or dedicated servers. Keeping the security updates current, managing any issues that may occur with email, and all the other headaches that go along with managing your own VPS or Dedicated server is more than we care to take on for the relatively small, practical difference between PHP and Ruby. For large projects, it may be worth the trouble, but for small to medium sized projects, PHP is much easier to deploy, less expensive to host, and the language is capable of taking on everything those types of sites require. For our projects, development time with PHP is not noticeably longer than with Ruby on Rails. Ruby on Rails integrates a lot of things for the developer.

There is ActiveRecord for managing the link between models and the database, migrations for keeping development and live databases in sync, built in testing, the ajax – prototype javascript library is included, and you get a well defined file system structure. While it may not all be packaged together as well, PHP can do all of the above.

Thank you for reading this and I would love to read your comments! Also subscribe to our RSS.

8 Great CSS Frameworks

Well, I guess I’m going to work backwords. There are three layers to the frontend; behaviour, presentation and markup. We’ve done behavior so we’re onto presentational now. CSS Frameworks have been all the buzz lately, we’ve had ones that use python ways of code then regenerate it as css, ones that are specifically for forms and an awesome one which is just for styling print!

Personally I find frameworks to much hassle, I have my own little framework but that is only really 20 or so lines. I might share it with all of you in the coming weeks if you would like it. Now here they are!

1. 960 Grid System – The 960 Grid System is an effort to streamline web development workflow by providing commonly used dimensions, based on a width of 960 pixels. There are two variants: 12 and 16 columns, which can be used separately or in tandem.

2. Blueprint CSS – Blueprint is a CSS framework, which aims to cut down on your CSS development time. It gives you a solid CSS foundation to build your project on top of, with an easy-to-use grid, sensible typography, and even a stylesheet for printing.

3. Hartija – The owner of Hartija describes it as a “universal Cascading Style Sheets for web printing”. It’s extremely customizable and very user friendly.

4. Formy CSS – Formy is mini CSS Framework for building web forms.

5. Clever CSS – CleverCSS is a small markup language for CSS inspired by Python that can be used to build a style sheet in a clean and structured way. In many ways it’s cleaner and more powerful than CSS2 is.

6. SenCSS – SenCSS is a sensible standards CSS Framework. This means that SenCSS tries to supply standard styling for all repetitive parts of your CSS, allowing you to focus on the fun parts. In that sense, senCSS is a bit like a large CSS Reset.

7. Elements

Elements is a down to earth CSS framework. It was built to help designers write CSS faster and more efficient. Elements goes beyond being just a framework, it’s its own project workflow.It has everything you need to complete your project, which makes you and your clients happy. Read the Overview for more information.

8. LogicCSS – The Logic CSS framework is a collection of CSS files and PHP utilities to cut development times for web-standards compliant xHTML layouts.

This is just the tip of the iceberg, there are tones more css frameworks out there. I plan on releasing one for this site.

Improving Code Readability With CSS Styleguides

Once your latest project is finished, you are very likely to forget the structure of the project’s layout, with all its numerous classes, color schemes and type setting. To understand your code years after you’ve written it you need to make use of sensible code structuring. The latter can dramatically reduce complexity, improve code management and consequently simplify maintainability. However, how can you achieve sensible structuring? Well, there are a number of options. For instance, you can make use of comments — after all, there is always some area for useful hints, notes and, well, comments you can use afterwards, after the project has been deployed.

Indeed, developers came up with quite creative ways to use comments and text formatting to improve the maintainability of CSS-code. Such creative ways are usually combined into CSS styleguides — pieces of CSS-code which are supposed to provide developers with useful insights into the structure of the code and background information related to it.

This article presents 5 coding techniques which can dramatically improve management and simplify maintainability of your code. You can apply them to CSS, but also to any other stylesheet or programming language you are using.

1. Divide and conquer your code

First consider the structure of your layout and identify the most important modules in your CSS-code. In most cases it’s useful to choose the order of CSS-selectors according to the order of divisors (div’s) and classes in your layout. Before starting coding, group common elements in separate sections and title each group. For instance, you can select Global Styles (body, paragraphs, lists, etc), Layout, Headings, Text Styles, Navigation, Forms, Comments and Extras.

To clearly separate fragments of code, select appropriate flags or striking comments (the more *-symbols you have in your code, the more striking a heading is). In the stylesheet they will serve as a heading for each group. Before applying a preferred flag to your code, make sure you can immediately recognize single blocks when scanning through the code.

However, this approach might not be enough for large projects where a single module is too big. If it is the case, you might need to divide your code in multiple files to maintain overview of single groups of code fragments. In such situations master stylesheet is used to import groups. Using master-stylesheet you generate some unnecessary server requests, but the approach produces a clean and elegant code which is easy to reuse, easy to understand and also easy to maintain. And you also need to include only the master-file in your documents.

/*——————————————————————
[Master Stylesheet]

Project:    Smashing Magazine
Version:    1.1
Last change:    05/02/08 [fixed Float bug, vf]
Assigned to:    Vitaly Friedman (vf), Sven Lennartz (sl)
Primary use:    Magazine
——————————————————————-*/
@import "reset.css";
@import "layout.css";
@import "colors.css";
@import "typography.css";
@import "flash.css";
/* @import "debugging.css"; */

For large projects or large development team it is also useful to have a brief update log and some additional information about the project — e.g. you can put the information about who is this CSS-file assigned to and what is its primary use (e.g. Smashing Magazine, Smashing Jobs etc.).

Additionally, you can include a debugging CSS-code to take care of diagnostic styling in case you run in some problems. Consider using Eric Meyer’s Diagnostic Styling as a debugging stylesheet to test your CSS-code and fix problems.

2. Define a table of contents

To keep an overview of the structure of your code, you might want to consider defining a table of contents in the beginning of your CSS-files. One possibility of integrating a table of contents is to display a tree overview of your layout with IDs and classes used in each branch of the tree. You may want to use some keywords such as header-section or content-group to be able to jump to specific code immediately.

You may also select some important elements you are likely to change frequently — after the project is released. These classes and IDs may also appear in your table of contents, so once you’ll need to find them you’ll find them immediately — without scanning your whole code or remembering what class or ID you once used.

/*——————————————————————
[Layout]

* body
    + Header / #header
    + Content / #content
        – Left column / #leftcolumn
        – Right column / #rightcolumn
        – Sidebar / #sidebar
            – RSS / #rss
            – Search / #search
            – Boxes / .box
            – Sideblog / #sideblog
    + Footer / #footer

Navigation      #navbar
Advertisements      .ads
Content header      h2
——————————————————————-*/

…or like this:

/*——————————————————————
[Table of contents]

1. Body
    2. Header / #header
        2.1. Navigation / #navbar
    3. Content / #content
        3.1. Left column / #leftcolumn
        3.2. Right column / #rightcolumn
        3.3. Sidebar / #sidebar
            3.3.1. RSS / #rss
            3.3.2. Search / #search
            3.3.3. Boxes / .box
            3.3.4. Sideblog / #sideblog
            3.3.5. Advertisements / .ads
    4. Footer / #footer
——————————————————————-*/

Another approach is to use simple enumeration without indentation. In the exampe below, once you need to jump to the RSS-section you simply use a search tool to find 8. RSS in your code. That’s easy, quick and effective.

/*——————————————————————
[Table of contents]

1. Body
2. Header / #header
3. Navigation / #navbar
4. Content / #content
5. Left column / #leftcolumn
6. Right column / #rightcolumn
7. Sidebar / #sidebar
8. RSS / #rss
9. Search / #search
10. Boxes / .box
11. Sideblog / #sideblog
12. Advertisements / .ads
13. Footer / #footer
——————————————————————-*/
<!– some CSS-code –>

/*——————————————————————
[8. RSS / #rss]
*/
#rss { … }
#rss img { … }

Defining a table of contents you make it particularly easier for other people to read and understand your code. For large projects you may also print it out and have it in front of you when reading the code. When working in team, this advantage shouldn’t be underestimated. It can save a lot of time — for you and your colleagues.

3. Define your colors and typography

Since we don’t have CSS constants yet, we need to figure out some way to get a quick reference of “variables” we are using. In web development colors and typography can often be considered as “constants” — fixed values that are used throughout the code multiple times.

As Rachel Andrew states, “one way to get round the lack of constants in CSS is to create some definitions at the top of your CSS file in comments, to define constants. A common use for this is to create a color glossary. This means that you have a quick reference to the colors used in the site to avoid using alternates by mistake and, if you need to change the colors, you have a quick list to go down and do a search and replace.”

/*——————————————————————
# [Color codes]

# Dark grey (text): #333333
# Dark Blue (headings, links) #000066
# Mid Blue (header) #333399
# Light blue (top navigation) #CCCCFF
# Mid grey: #666666
# */

Alternatively, you can also describe color codes used in your layout. For a given color, you can display sections of your site which are using this color. Or vice versa — for a given design element you can describe the colors which are used there.

/*——————————————————————
[Color codes]

Background:    #ffffff (white)
Content:    #1e1e1e (light black)
Header h1:    #9caa3b (green)
Header h2:    #ee4117 (red)
Footer:        #b5cede (dark black)

a (standard):    #0040b6 (dark blue)
a (visited):    #5999de (light blue)
a (active):    #cc0000 (pink)
——————————————————————-*/

The same holds for typography. You can also add some important notes to understand the “system” behind your definitions.

/*——————————————————————
[Typography]

Body copy:        1.2em/1.6em Verdana, Helvetica, Arial, Geneva, sans-serif;
Headers:        2.7em/1.3em Helvetica, Arial, "Lucida Sans Unicode", Verdana, sans-serif;
Input, textarea:    1.1em Helvetica, Verdana, Geneva, Arial, sans-serif;
Sidebar heading:    1.5em Helvetica, Trebuchet MS, Arial, sans-serif;

Notes:    decreasing heading by 0.4em with every subsequent heading level
——————————————————————-*/

4. Order CSS properties

When writing the code often it’s useful to apply some special formatting to order CSS properties — to make the code more readable, more structured and therefore more intuitive. There is a variety of grouping schemes developers use in their projects. Some developers tend to put colors and fonts first; other developers prefer to put “more important” assignments such as those related to positioning and floats first. Similarly, elements are also often sorted according to the topology of the site and the structure of the layout. This approach can be applied to CSS selectors as well:

    body,
    h1, h2, h3,
    p, ul, li,
    form {
        border: 0;
        margin: 0;
        padding: 0;
    }

Some developers use a more interesting approach — they group properties in an alphabetical order. Here it’s important to mention that alphabetizing CSS properties may lead to some problems in some browsers. You may need to make sure that no changes are produced as a result of your ordering manipulations.

body {
    background: #fdfdfd;
    color: #333;
    font-size: 1em;
    line-height: 1.4;
    margin: 0;
    padding: 0;
}

Whatever grouping format you are using, make sure you clearly define the format and the objective you want to achieve. Your colleagues will thank you for your efforts. And you’ll thank them for sticking to your format.

5. Indentation is your friend!

For better overview of your code you might consider using one-liners for brief fragments of code. This style might produce messy results if you define more than 3 attributes for a given selector. However, used moderately, you can highlight dependencies between all elements of the same class. This technique will dramatically increase code readability when you have to find some specific element in your stylesheet.

#main-column { display: inline; float: left; width: 30em; }
        #main-column h1 { font-family: Georgia, "Times New Roman", Times, serif; margin-bottom: 20px; }
        #main-column p { color: #333; }

You remember exactly what you did and can jump back in there and fix it. But what if you made a lot of changes that day, or you just simply can’t remember? Chris Coyier suggests an interesting solution for highlighting recent changes in your CSS-code. Simply indenting new or changed lines in your CSS you can make recent changes in your code more visible. You can as well use some comments keywords (e.g. @new) — you’ll be able to jump to the occurrences of the keyword and undo changes once you’ve found some problems.

#sidebar ul li a {
     display: block;
     background-color: #ccc;
          border-bottom: 1px solid #999; /* @new */
     margin: 3px 0 3px 0;
          padding: 3px; /* @new */
}

Conclusion

CSS styleguides are helpful if and only if they are used properly. Keep in mind that you should remove every styleguide which doesn’t effectively help you to get a better understanding of the code or achieve a well-structured code. Avoid too many styleguides for too many elements bundled in too many groups. Your goal is to achieve a readable and maintainable code. Stick to it and you’ll save yourself a lot of trouble.

XHTML 2 or HTML 5 Which one is for you?

Overview of XHTML 2.0

XHTML 2.0 is based solely on XML, forgoing the SGML heritage and syntax peculiarities present in current web markup. XHTML 2.0 is supposed to be a “general-purpose language,” with a minimal default feature set that is easy to extend using CSS and other technologies (XForms, XML Events, etc). It’s a modular approach that allows the XHTML2 group to focus on generic document markup, while others develop mechanisms for presentation, interactivity, document construction, etc.

Priority one for the XHTML2 working group is to further separate document content and structure from document presentation. Other goals include increased usability and accessibility, improved internationalization, more device independence, less scripting, and better integration with the Semantic Web. The group has been less concerned with backward compatibility than their predecessors (and the HTML working group), which has led them to drop some of the syntactic baggage present in earlier incarnations of HTML. The result is a cleaner, more concise language that corrects many of Web markup’s past indiscretions.

Overview of HTML 5

While XHTML 2.0 aims to be revolutionary, the HTML working group has taken a more pragmatic approach and designed HTML 5 as an evolutionary technology. That is to say, HTML 5 is an incremental step forward that remains mostly compatible with the current HTML 4/XHTML 1 standards. However, HTML 5 offers a host of changes and extensions to HTML 4/XHTML 1 that address many of the faults in these earlier specifications.

HTML 5 is about moving HTML away from document markup, and turning it into a language for web applications. To that end, much of the specification focuses on creating a more robust, feature-ful client side environment for web application development by providing a variety of APIs. Among other things, the spec stipulates that complying implementations must provide client-side persistent storage (both key/value and SQL storage engines), audio and video playback APIs, 2D drawing through the canvas element, cross-document messaging, server-sent events, and a networking API.

The HTML 5 specification maintains an SGML-like syntax that is compatible with the current HTML specifications (though some of the more esoteric features of SGML are no longer supported). Also included in the specification is a second “XML Serialization” which allows developers to serve valid XML documents as well. Again, by maintaining an SGML-like serialization the HTML 5 working group has struck a balance between pragmatism and progress. Developers can choose to markup content using either the HTML serialization (which looks more like HTML 4.x) or the XML serialization (which looks more like XHTML 1.x).

Similar Features

It shouldn’t be too surprising that both working groups are proposing a number of similar features. These features address familiar pain points for web developers, and should be welcome additions to the next generation of markup languages.

Removal of Presentational Elements

A number of elements have been removed from both XHTML 2.0 and HTML 5 because they are considered purely presentational. The consensus is that presentation should be handled using style sheets.

HTML 5 and XHTML 2.0 documents cannot contain these elements: basefont, big, font, s, strike, tt, and u. XHTML 2.0 also removes the small, b, i, and hr elements, while HTML 5 redefines them with non-presentational meanings. In XHTML 2.0, the hr element has been replaced with separator in an attempt to reduce confusion (since the hr element, which stands for horizontal rule, is not necessarily either of those things).

Navigation Lists

Navigation lists have been introduced in both XHTML 2.0 and HTML 5. In XHTML 2.0, navigation is marked up using the new nl element. Navigation lists must start with a child label element that defines the list title. Following the title, one or more li elements are used to markup links. Also new in XHTML 2.0 is the ability to create a hyperlink from any element using the href attribute. Combining these features produces simple, lightweight navigation markup:

In HTML 5, the new nav element has been introduced for this purpose. Unfortunately, nav is not a list element, so it cannot contain child li elements to logically organize links (perhaps a new idiom will develop). And since anchor tags are still required to create hyperlinks in HTML 5, navigation markup is not quite as elegant:

Enhanced Forms

Both specifications have new features to create more robust, consistent forms with less scripting. In XHTML 2.0, standard HTML forms are dropped completely in favor of the more comprehensive XForms standard. The XHTML2 working group does not control this standard, but references it from the XHTML 2.0 specification. To facilitate reuse, XForms separates the data being collected from the markup of the controls. It’s a robust and powerful language, but a full description is way beyond the scope of this post. Suffice it to say, there will be a bit of a learning curve for web developers trying to get up to speed with this technology.

HTML 5 retains the familiar HTML forms, but adds several new data types to simplify development and improve usability. In HTML 5, several new types of input elements have been introduced for email addresses, URLs, dates and times, and numeric data. This will allow user agents to provide more sophisticated user interfaces (e.g., calendar date pickers), integrate with other applications (e.g., pulling addresses from Outlook or Address Book), and validate user input before posting data to the server (less client-side javascript validation).

Semantic Markup

Both working groups have embraced the coming Semantic Web by allowing developers to embed richer metadata in their documents. As with forms, the XHTML2 working group has embraced a more sophisticated technology, while the HTML working group has kept things simple.

In XHTML 2.0, metadata can be embedded by using several new global attributes from the Metainformation Attributes Module. In particular, the new global role attribute is intended to describe the meaning of a given element in the context of the document. The technical term is Embedding Structured Data in Web Pages. Again, the group leverages an existing standard by referencing RDF. The technology is extremely powerful, but it’s also complicated.

The HTML working group has taken an approach that feels more like microformats by overloading the class attribute with a predefined set of reserved classes to represent various types of data. The specification currently lists seven reserved classes: copyright, error, example, issue, note, search, and warning. While overloading the class attribute like this might be confusing, it’s unlikely that user agents will render elements with these classes differently. And the class names are specific enough that there’s little worry: if an element has its class set to copyright, it’s probably a copyright whether the developer knew about the reserved classes or not.

Only in HTML 5

There are several new features that the HTML 5 specification describes that have no counterparts in XHTML 2.0.

Web Application APIs

HTML 5 introduces several APIs that will drastically improve the client-side web development environment. These APIs are what set HTML 5 apart as a proposal for a technology stack for Web Applications, rather than simply a markup language for documents. It should be noted that the details of these APIs are being worked out by the Web API working group, so they may be adopted with or without the rest of HTML 5. The new APIs, and corresponding elements are:

  • A 2D drawing API using the canvas element.
  • An audio and video playback API, supporting the ability to offer multiple formats to user agents, which can be used with the new video and audio elements.
  • Persistent storage on the client-side with support for both key/value and SQL databases.
  • An offline web application API (similar to Google Gears).
  • An API that allows Web Applications to register themselves for certain protocols or MIME types.
  • An editing API that can be used in combination with the global contenteditable attribute.
  • A drag & drop API that can be used with the draggable attribute.
  • A network API allowing Web applications to communicate using TCP.
  • An API that exposes the browser history, allowing applications to add to it so they don’t break the back button.
  • A cross-document messaging API.
  • Server-sent events in combination with the new event-source element.

New Elements

Several new elements are being introduced by HTML 5 that aren’t available in XHTML 2.0:

  • figure represents an image or graphic with a caption. A nested legend represents the caption, while a normal img element is used for the image.
  • m represents text that has been marked in some way. It could be used to highly search terms in resulting documents, for example.
  • time represents dates and time.
  • meter represents a measurement.
  • datagrid represents an interactive tree list or tabular data.
  • command represents a command that the user can invoke.
  • event-source is used to “catch” server sent events.
  • output represents some type of output, such as from a calculation done through scripting.
  • progress represents a completion of a task, such as downloading or when performing a series of expensive operations.

In addition, several new elements will help semantically markup the parts of a document. They’re fairly self explanatory: section, article, header, footer, and aside. And a new dialog element is designed to represent conversations using child dt elements for the speaker’s name and dd elements for the text.

Track Users by Pinging URIs

The new ping attribute can be used on the a and area elements to do user tracking. Rather than using redirects, or relying on javascript, the ping attribute allows you to specify a space separated list of URIs that should be pinged when the hyperlink is followed.

Only in XHTML 2.0

Also notable are the following new features that are available only in XHTML 2.0.

Any Element can be a Hyperlink

In XHTML 2.0, any element can be the source of a hyperlink — the href attribute can appear on any element. With this change the a element is no longer necessary, but it is retained.

Any Element can be an Image (or other resource)

In XHTML 2.0, the img element has been dropped. No worries, though — any element can now be an image. The idea is that all images have a “long description” that is equivalent to the image itself. By placing a src attribute on any element, you’re telling the user agent to load that resource in place of the element. If, for whatever reason, the resource is unavailable, the element is used instead. This allows developers to provide multiple equivalent resources using different file formats and representations by nesting elements within one another.

Lines Replace Line Breaks

The venerable br element, used to insert line breaks, has also been dropped from XHTML 2.0. The new l element is being introduced to replace it. l represents a line of text, and behaves like a span followed by a br in today’s markup.

New Heading Construct

The new h and section elements have been introduced to replace the numbered h1 through h6 elements. The goal is to accurately represent the hierarchical structure of a document. The current numbered headings are linear, not nested. By nesting section and h elements within parent sections the document structure is made explicit.

New Elements

The XHTML2 working group has focused on creating a more generic, simplified language. To that end, they’ve refrained from adding numerous specialized elements to represent different types of content. They argue that the new role attribute provides a mechanism for including rich metadata, making specialized elements unnecessary. That said, a couple new elements were included:

  • blockcode represents computer code.
  • di represents a group of related terms and definitions in a dl (definition list). This is useful for words with multiple definitions, or multiple spellings.
  • handler represents a scripted event handler, with a type attribute specifying the handler language. If the user agent doesn’t understand the language, the handler’s children are processed (otherwise they’re ignored). Handlers may be nested to provide multiple implementations in various languages.

Conclusion

Both proposals look promising, with lots of new features that address common web development problems. But neither specification is an official recommendation, and it’s likely to stay that way for some time.

Despite its late start, the HTML 5 working group seems to have more industry support, and is further along in the recommendation process. Their goal is to have a complete spec, with multiple interoperable implementations, by late 2010 (as I said before, though, the W3C has already missed some milestones in the approval process). With industry support from most of the major browser vendors (the only notable exception being Microsoft) it’s likely that this specification will be implemented quickly and consistently once it’s reached a stable state.

What everyone wants to avoid is another standards war. Fortunately, since both languages support XML namespaces (or, in the case of the HTML serialization of HTML 5, DOCTYPE switching) it’s unlikely that we’ll see the sort of browser dependent behavior we did in the 1990s. Standards wars aside, the future looks bright for web development. These new markup features and APIs will provide a rich environment for web development that should narrow the gap between Web and Desktop applications.

If you’ve got any thoughts, comments or suggestions for things we could add, leave a comment! Also please Subscribe to our RSS for latest tips, tricks and examples on cutting edge stuff.