Nov 16, 2009

CSS Best Practices and Cross-browser Compatibility

This article is consolidation of the best practices which are followed or taken care during the development when a web page is styled using a external or inline style sheet referred to as CSS (Cascading Style Sheet). The best practices are arrived at after evaluating and analyzing the working web pages. Some of the concepts shared in this article are widely available on the internet but few are exclusively on the basis of experience and learning. Cascading style sheets are, in general terms, a collection of formatting rules that control the appearance, or presentation, of content on a web page. Implementing CSS within a page or site is done in one of three ways:

  • Inline: A one-time style applied within the code as an attribute of a given element (or tag).
  • Embedded: A style sheet declaration in the head of the document that will only effect that single page on the site.
  • External: A physical CSS file containing rules (styles) that is linked to from multiple pages within the site.

This article can be helpful or can act as a reference for any project which has web-based solutions.

Coding Practices

1. Use the correct – Doctype, Document Type Definition
Choosing a suitable Doctype for your site is the best thing you should do when it comes to writing (X)HTML code. This block of code helps the browser render properly the content of the site and it is also the first needed code for standards compliant (X)HTML documents. As a personal recommendation I think the best Doctype is XHTML 1 – Strict.

<!DOCTYPE html PUBLIC-//W3C//DTD XHTML 1.0 Strict//EN>

2. Make it Readable

The readability of your CSS is incredibly important, though most people overlook why it's important. Great readability of your CSS makes it much easier to maintain in the future, as you'll be able to find elements quicker. Also, you'll never know who might need to look at your code later on.

Group 1: All on one line


.someDiv { background: red; padding: 2em; border: 1px solid black; }

Group 2: Each style gets its own line

.someDiv {
background: red;
padding: 2em;
border: 1px solid black;

Both practices are perfectly acceptable, though you'll generally find that group two despises group one! Just remember - choose the method that looks best TO YOU. That's all that matters.

3. Keep it Consistent

Along the lines of keeping your code readable is making sure that the CSS is consistent. You should start to develop your own "sub-language" of CSS that allows you to quickly name things. There are certain classes that I create in nearly every theme, and I use the same name each time. For example, I use ".caption-right" to float images which contain a caption to the right.

Think about things like whether or not you'll use underscores or dashes in your ID's and class names, and in what cases you'll use them. When you start creating your own standards for CSS, you'll become much more proficient.

4. Use a Reset

Most CSS frameworks have a reset built-in, but if you're not going to use one then at least consider using a reset. Resets essentially eliminate browser inconsistencies such as heights, font sizes, margins, headings, etc. The reset allows your layout look consistent in all browsers.

The MeyerWeb ( is a popular reset, along with Yahoo's developer reset ( Or you could always roll your own reset if that tickles your fancy.

html, body, div, span,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
img, ins, kbd, q, s, samp,
small, strike, strong,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
body {
line-height: 1;
ol, ul {
list-style: none;
blockquote, q {
quotes: none;
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
table {
border-collapse: collapse;
border-spacing: 0;

5. Organize the Stylesheet with a Top-down Structure

It always makes sense to lay your stylesheet out in a way that allows you to quickly find parts of your code. I recommend a top-down format that tackles styles as they appear in the source code. So, an example stylesheet might be ordered like this:

  • Generic classes (body, a, p, h1, etc.)

  • #header

  • #nav-menu

  • #main-content

Don't forget to comment each section!

/****** main content *********/
styles goes here...
/****** footer *********/
styles go here...

6. Combine Elements

Elements in a stylesheet sometimes share properties. Instead of re-writing previous code, why not just combine them? For example, your h1, h2, and h3 elements might all share the same font and color:

h1, h2, h3 {font-family: tahoma, color: #333}

We could add unique characteristics to each of these header styles if we wanted (ie. h1 {size: 2.1em}) later in the stylesheet.

7. Create Your HTML First

Many designers create their CSS at the same time they create the HTML. It seems logical to create both at the same time, but actually you'll save even more time if you create the entire HTML mockup first. The reasoning behind this method is that you know all the elements of your site layout, but you don't know what CSS you'll need with your design. Creating the HTML layout first allows you to visualize the entire page as a whole, and allows you to think of your CSS in a more holistic, top-down manner.

8. Use Multiple Classes

Sometimes it's beneficial to add multiple classes to an element. Let's say that you have a <div> "box" that you want to float right, and you've already got a class .right in your CSS that floats everything to the right. You can simply add an extra class in the declaration, like so:

<div class="box right"></div>

Be very careful when using ids and class-names like "left" and "right." How come? Let's imagine that, down the road, you decide that you'd rather see the box floated to the LEFT. In this case, you'd have to return to your HTML and change the class-name - all in order to adjust the presentation of the page.

This is not semantic. Remember - HTML is for markup and content. CSS is for presentation.

If you must return to your HTML to change the presentation (or styling) of the page, you're doing it wrong!

9. Use Shorthand

You can shrink your code considerably by using shorthand when crafting your CSS. For elements like padding, margin, font and some others, you can combine styles in one line. For example, a div might have these styles:

#crayon {
margin-left: 5px;
margin-right: 7px;
margin-top: 8px;

You could combine those styles in one line, like so:

#crayon {
margin: 8px 7px 0px 5px; // top, rightright, bottombottom, and left values, respectively.

10. Comment your CSS

Just like any other language, it's a great idea to comment your code in sections. To add a comment, simply add /* behind the comment, and */ to close it, like so:

/* Here's how you comment CSS */

11. Understand the Difference between Block vs. Inline Elements

Block elements are elements that naturally clear each line after they're declared, spanning the whole width of the available space. Inline elements take only as much space as they need, and don't force a new line after they're used.

Here are the lists of elements that are either inline or block:

span, a, strong, em, img, br, input, abbr, acronym

And the block elements:

div, h1...h6, p, ul, li, table, blockquote, pre, form

12. Don’t use too many id’s and classes

In the past, I used for most of my tags id’s and classes. That was wrong. Instead of a crowded code you can choose to use CSS selectors in order to identify and stylize content. This is another measure in keeping your code clean.

13. Check for Closed Elements First When Debugging

If you're noticing that your design looks a distorted, there's a good chance it's because you've left off a closing </div>. You can use the XHTML validator ( help sniff out all sorts of errors too.

14. Never Use Inline Styles

When you're hard at work on your markup, sometimes it can be tempting to take the easy route and sneak in a bit of styling. <p style="color: red;"> I'm going to make this text red so that it really stands out and makes people take notice! </p>

Sure -- it looks harmless enough. However, this points to an error in your coding practices.

When creating your markup, don't even think about the styling yet. You only begin adding styles once the page has been completely coded. Instead, finish your markup, and then reference that P tag from your external stylesheet.

Better we use like below

#someElement > p {
color: red;

15. Place all External CSS Files within the Head Tag

Technically, you can place stylesheets anywhere you like. However, the HTML specification recommends that they be placed within the document HEAD tag. The primary benefit is that your pages will seemingly load faster.

16. Learn How to Target IE

You'll undoubtedly find yourself screaming at IE during some point or another. It's actually become a bonding experience for the community. The first step, once you've completed your primary CSS file, is to create a unique "ie.css" file. You can then reference it only for IE by using the following code.

<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" media="screen" href="path/to/ie.css"

This code says, "If the user's browser is Internet Explorer 6 or lower, import this stylesheet. Otherwise, do nothing." If you need to compensate for IE7 as well, simply replace "lt" with "lte" (less than or equal to).

17. Style ALL Elements

This best practice is especially true when designing for clients. Just because you haven't use a blockquote doesn't mean that the client won't. Never use ordered lists? That doesn't mean he won't! Do yourself a service and create a special page specifically to show off the styling of every element:

ul, ol, p, h1-h6, blockquotes, etc.

18. Alphabetize your Properties

While this is more of a frivolous tip, it can come in handy for quick scanning.

#cotton-candy {
color: #fff;
float: left;
font-weight: bold;
height: 200px;
margin: 0;
padding: 0;
width: 150px;

19. Make Use of Generic Classes

You'll find that there are certain styles that you're applying over and over. Instead of adding that particular style to each ID, you can create generic classes and add them to the IDs or other CSS classes.

For example, I find myself using float:right and float:left over an over in my designs. So I simply add the classes .left and .right to my stylesheet, and reference it in the elements.

.left {float:left}
.rightright {float:rightright}
<div id="coolbox" class="left">...</div>

This way you don't have to constantly add "float:left" to all the elements that need to be floated.

20. Use "Margin: 0 auto" to Center Layouts

Many beginners to CSS can't figure out why you can't simply use float: center to achieve that centered effect on block-level elements. If only it were that easy! Unfortunately, you'll need to use

  • margin: 0 auto; // top, bottombottom - and left, rightright values, respectively.

    to center divs, paragraphs or other elements in your layout. 

By declaring that both the left AND the right margins of an element must be identical, the have no choice but to center the element within its containing element.

21. Don't Just Wrap a DIV Around It

When starting out, there's a temptation to wrap a div with an ID or class around an element and create a style for it.

<div class="header-text"><h1>Header Text</h1></div>

Sometimes it might seem easier to just create unique element styles like the above example, but you'll start to clutter your stylesheet. This would have worked just fine:

<h1>Header Text</h1>

Then you can easily add a style to the h1 instead of a parent div.

22. Hack Less

Avoid using as little browser-specific hacks if at all possible. There is a tremendous pressure to make sure that designs look consistent across all browsers, but using hacks only makes your designs harder to maintain in the future. Plus, using a reset file can eliminate nearly all of the rendering irregularities between browsers.

23. Use Absolute Positioning Sparingly

Absolute positioning ( is a handy aspect of CSS that allows you to define where exactly an element should be positioned on a page to the exact pixel. However, because of absolute positioning disregard for other elements on the page, the layouts can get quite hairy if there are multiple absolutely positioned elements running around the layout.

24. Use Text-transform

Text-transform is a highly-useful CSS property that allows you to "standardize" how text is formatted on your site. For example, say you're wanting to create some headers that only have lowercase letters. Just add the text-transform property to the header style like so:

text-transform: lowercase;

Now all of the letters in the header will be lowercase by default. Text-transform allows you to modify your text (first letter capitalized, all letters capitalized, or all lowercase) with a simple property.

25. Don't use Negative Margins to Hide Your h1

Oftentimes people will use an image for their header text, and then either use display:none or a negative margin to float the h1 off the page. Google might think it's spam.

26. Ems vs. Pixels

There's always been a strong debate as to whether it's better to use pixels (px) or ems (em) when defining font sizes. Pixels are a more static way to define font sizes, and ems are more scalable with different browser sizes and mobile devices. With the advent of many different types of web browsing (laptop, mobile, etc.), ems are increasingly becoming the default for font size measurements as they allow the greatest form of flexibility. also has a great article on the differences between the measurement sizes (

27. Don't Underestimate the List

Lists are a great way to present data in a structured format that's easy to modify the style. Thanks to the display property, you don't have to just use the list as a text attribute. Lists are also great for creating navigation menus and things of the sort.

Many beginners use divs to make each element in the list because they don't understand how to properly utilize them. It's well worth the effort to use brush up on learning list elements to structure data in the future.

28. Avoid Extra Selectors

It's easy to unknowingly add extra selectors to our CSS that clutters the stylesheet. One common example of adding extra selectors is with lists. 

body #container .someclass ul li {....}

In this instance, just the .someclass li would have worked just fine.

.someclass li {...}

Adding extra selectors won't bring Armageddon or anything of the sort, but they do keep your CSS from being as simple and clean as possible.

29. Add Margins and Padding to All

Different browsers render elements differently. IE renders certain elements differently than Firefox. IE 6 renders elements differently than IE 7 and IE 8. While the browsers are starting to adhere more closely to W3C standards, they're still not perfect (*cough IE cough*).

One of the main differences between versions of browsers is how padding and margins are rendered. If you're not already using a reset, you might want to define the margin and padding for all elements on the page, to be on the safe side. You can do this quickly with a global reset, like so:

* {margin:0;padding:0;}

Now all elements have a padding and margin of 0, unless defined by another style in the stylesheet. The problem is that, because EVERYTHING is zeroed out with this method, you'll potentially cause yourself more harm than help. Are you sure that you

want every single element's margins and padding zeroed? If so - that's perfectly acceptable. But at least consider it.

30. Line 'em Up!

Generally speaking, you should strive to line up your elements as best as possible. Take a look at you favorite designs. Did you notice how each heading, icon,  paragraph, and logo lines up with something else on the page? Not doing this is one of the biggest signs of a beginner.

31. Use Multiple Stylesheets

Depending on the complexity of the design and the size of the site, it's sometimes easier to make smaller, multiple stylesheets instead of one giant stylesheet. Aside from it being easier for the designer to manage, multiple stylesheets allow you to leave out CSS on certain pages that don't need them. For example, I might having a polling program that would have a unique set of styles. Instead of including the poll styles to the main stylesheet, I could just create a poll.css and the stylesheet only to the pages that show the poll. <editors-note> However, be sure to consider the number of HTTP requests that are being made. Many designers prefer to develop with multiple stylesheets, and then combine them into one file. This reduces the number of HTTP requests to one. Also, the entire file will be cached on the user's computer.

32. Validate your HTML and CSS

Validating your CSS and XHTML does more than give a sense of pride: it helps you quickly spot errors in your code. If you're working on a design and for some reason things just aren't looking right, try running the markup and CSS validator and see what errors pop up. Usually you'll find that you forgot to  close a div somewhere, or a missed semi-colon in a CSS property.

33. Test in multiple browsers

Test in multiple browsers as you go. Generally, you'll find that non-IE browsers behave similarly and IE is a special case - especially if you follow the advice above. When necessary, you can add IE hacks in a separate stylesheet and only load it for IE users. ( is a good place for hunting down random browser differences. ( can help show how your page will be displayed in an assortment of browsers and operating systems.

Cross-browser compatibility

Browsers parse code differently. Internet viewers use a variety of browsers. It is a  good idea to design your website so the vast majority of viewers can get the full  benefit of your site.

The best website designs are compatible with the most popular browsers, thus being cross browser compatible. Standard coding practices and cross-browser compatibility goes hand in hand.

Code the web page in the latest version of the browser and then use separate style sheet for the browsers which are creating challenges.

Test, test, test in browsers. I would recommend having at least three browsers downloaded onto your computer: Internet Explorer, Firefox and Opera/Safari. The browsers listed cost nothing to download.

The more testing you do of your site while it is being constructed, the more sure you  can be of its appearance to your audience. Frequent testing also reveals problems early in the design process, making them easier to pinpoint.

Browser Compatibility Check for Internet Explorer Versions from 5.5 to 8  (

IETester is a free WebBrowser that allows you to have the rendering and JavaScript engines of IE8, IE7 IE 6 and IE5.5 on Windows 7, Vista and XP, as well as the installed  IE in the same process. (

Check Browser Compatibility, Cross Platform Browser Test - Browsershots

More info :

Links to useful add-ons

Web Developer ( A straight-forward add-on that gives you some extra menu selections for using and disabling different cascading style sheets so you can test them out.

HttpFox ( HttpFox monitors all incoming and outgoing HTTP traffic between the browser and servers. Reports include request and response headers, sent and received cookies, querystring parameters, POST parameters and response body.

HTML Validator ( Just as the name of this addon implies, HTML Validator is all about making sure that your code is up to par. You can also check pages that you are visiting, and thanks to a little indicator in the corner of your browser, you’ll quickly see if the page is in compliance or has errors. Once you click on the indicator you will see a full version of the code that will identify what the problems are.

Firebug ( Probably the most essential tool for any developer using Firefox. Firebug will allow you to monitor the activities of a page you are visiting, write new code, debug what you’ve already worked on and a whole lot more.

YSlow ( YSlow is a Firefox add-on that integrates with the popular Firebug tool for Firefox. YSlow applies three predefined rulesets or a user-defined ruleset to test the performance of a page. Then, it suggests things you could do to improve it.

IE Tab ( This is a great tool for web developers, since you can easily see how your web page displayed in IE with just one click and then switch back to Firefox.

Internet Explorer Developer Toolbar

( IE Developer Toolbar is the IE add-on that provides me the features I like in my Firefox extensions.

These guidelines can help you grow as a coder and also will give a professional feeling to your Stylesheets. Although the standards are not yet fully supported by all  browsers in all circumstances, creating standards-compatible pages is the best way to ensure good rendering. As always, learning to use new technologies will take some time and will give you some incompatibility headaches. Nonetheless the results will be well worth the investment.


Anonymous said...

I think that progressive enhancement and using web standards is the way to design for the future. I also think you did a good job of touching some small important factors about browser compatibility, and there are still people out there designing for specific browsers. Maybe one day it will be a perfect world, but until then keep the word out there.
-Glenn Powell

Text Widget

Copyright © Vinay's Blog | Powered by Blogger

Design by | Blogger Theme by