Use Efficient CSS Selectors for Fast Loading

Posted on January 24, 2012 in HTML/CSS Category

Maybe some of Web Designers had problems with writing a clean CSS code to their web page. In this article we will explain how to use efficient CSS selectors and tag keys on your blog or website, avoiding all unnecessary things that can cause problems to your page.

Efficient and Inefficient Examples

In the image below we will explain how browser will render the CSS that you are writting:

Examples of Efficient CSS Selectors

As you saw in the image above the first example has fewer classes defined and this is wrong. Every time the page is being loaded, browser will try to search through all specified tag keys and selectors from your CSS file and this will take time for every search request.

What Selectors We Should Use?

The best results for rendering the page more faster and search through elements, is to use #id attributes instead of .classes, but only on the main element. See the example below to understand:

We have a <table> or <div> (which is the main box for our content) and inside are different tags such as <a>, <strong> or <p>.

				<a href="#">Link</a>

				<li>Some <strong>text</strong></li>

If you use a global CSS, try to write as clean as possible. You can refer to <table> tag only, or <table><p>, or <table><ul>.

If you use styles for different content try to group them generally, because in this way browser will find your elements more faster. See the HTML and efficient CSS classes examples below:

<table id="maintable">
			<p class="firstp">
				<a href="#">Link</a>

			<ul class="firstlist">
				<li>Some <strong>text</strong></li>

Every tag key should have maximum one descendant selector. See the CSS example below related to the HTML above:

/* Wrong CSS */
#maintable tr td { }
#maintable tr td p a { }
#maintable ul li { }
#maintable td ul li { }
#maintable li strong { }

/* Good and Efficient CSS */
#maintable { }
#maintable tr { }
#maintable td { }
#maintable p { }
.firstp a { }
.firstlist li { }
.firstlist a { }
.firstlist strong { }

Very Inefficient Rules!

Never use classes overly tag keys with multiple selectors. This may cause your page to load slower.

div.someclass a img { }
table.someclass ul li { }

Never use the pseudo-selector ":hover" on non-anchor elements. This can cause performance problems in Internet Explorer 7 and 8 when a strict doctype is used.

img:hover { }
input:hover { }

In conclusion, to have a clean and efficient CSS and a fast rendering for your pages, you should follow the rules above.

Related Articles
Hint: Wrap your code syntax (html, css or others) between <pre> and </pre> tags. All comments are moderated.

× 8 = thirty two

Subscribe by E-mail

HTML-TUTS is built under the mighty WordPress platform.