<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Bright Lines &#187; selector</title>
	<atom:link href="http://www.thebrightlines.com/tag/selector/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.thebrightlines.com</link>
	<description>HTML, CSS, Javascript and more</description>
	<lastBuildDate>Tue, 17 Jan 2012 22:00:35 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>CSS performance, who cares?</title>
		<link>http://www.thebrightlines.com/2010/07/28/css-performance-who-cares/</link>
		<comments>http://www.thebrightlines.com/2010/07/28/css-performance-who-cares/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 05:11:40 +0000</pubDate>
		<dc:creator>Wouter Bos</dc:creator>
				<category><![CDATA[Browsers]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Optimization]]></category>
		<category><![CDATA[efficiency]]></category>
		<category><![CDATA[rendering]]></category>
		<category><![CDATA[selector]]></category>

		<guid isPermaLink="false">http://www.thebrightlines.com/?p=648</guid>
		<description><![CDATA[You probably didn't notice it, but the way you write CSS affects the rendering speed of the browser. Should you care about that? Most likely not, but it is possible to freeze your web page with inefficient selectors.]]></description>
			<content:encoded><![CDATA[<p>Lately I read the following text in <em>Building iPhone Apps with HTML, CSS, and JavaScript</em> (O&#8217;Reilly) on using ID&#8217;s in CSS:</p>
<blockquote cite="http://oreilly.com/catalog/9780596805784?cmp=il-orm-ofps-iphoneapps"><p>&#8220;There are differences between class and id. Class attributes should be used when you have more than one item on the page with the same class value. Conversely, id values have to be unique to a page.</p>
<p>When I first learned this, I figured I’d just always use class attributes so I wouldn’t have to worry about whether I was duping an id value. However, selecting elements by id is much faster than selecting them by class, so you can hurt your performance by overusing class selectors.&#8221;</p></blockquote>
<p>Huh? I never use ID&#8217;s in CSS selectors, but I never experienced slow rendering either. I wanted to test if it&#8217;s stupid not to use ID&#8217;s.</p>
<p>First I wanted to see if it was even able to create a CSS that was hard to parse. Google has a nice article about <a href="http://code.google.com/speed/page-speed/docs/rendering.html#UseEfficientCSSSelectors">writing efficient CSS selectors</a>, so that seemed like a good start before setting up a test. In short there are 2 things that make a fast CSS selector:</p>
<ul>
<li><strong>Make rules as specific as possible</strong><br />
This means that <code>div.content</code> is faster than <code>*</code>.<br />
You have to be especially specific with the rightmost selector, since the browser reads CSS selector from right to left.</li>
<li><strong>Avoid (large) descendant rules</strong><br />
An example of a descendant rule is <code>div.content div.column1 div.columnHeader h2</code>. Descendant rules are less efficient than rules with a single selector, like <code>h2</code>.</li>
</ul>
<h2>Test 1: setting up extremely inefficient CSS</h2>
<p>The most inefficient selector by far is <code>*</code>. Combined with large descendant rules you get extremely inefficient selectors:</p>
<pre name="code" class="css:nogutter">
* * * * * * * * * {
	background: #ff1;
}
* * * * {
	background: #ff2;
}
* * * * * * * {
	background: #ff3;
}
</pre>
<p>I created a CSS file of about 20KB in size with 3600 asterisks characters (*). I combined it with a very large HTML file (1MB) with 9000 opening HTML brackets (<). Because I only wanted to test the CSS rendering, I added the following JavaScript to be able to load the CSS file on my local computer <em>after</em> the page was loaded.</p>
<pre name="code" class="javascript:nogutter">
	<a href="javascript:loadCSS('default.css')">Load CSS</a>
	<script type="text/javascript">
		function loadCSS(url) {
			var fileref=document.createElement("link");
			fileref.setAttribute("rel", "stylesheet");
			fileref.setAttribute("type", "text/css");
			fileref.setAttribute("href", url);
			document.getElementsByTagName("head")[0].appendChild(fileref);
		}
	</script>
</pre>
<h3>Results Test 1</h3>
<table>
<thead>
<tr>
<th>Browser</th>
<th>Render time (sec)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Firefox 3.6</td>
<td>2</td>
</tr>
<tr>
<td>IE 8</td>
<td>4</td>
</tr>
<tr>
<td>IE 7</td>
<td>6</td>
</tr>
<tr>
<td>IE 6</td>
<td>11</td>
</tr>
<tr>
<td>Chrome 6</td>
<td>4</td>
</tr>
</tbody>
</table>
<p><em>All tests were done on my computer (Vista with Intel Duo Core @ 2.4GHz) except for IE7 and IE6. IE7 was tested on a Vista machine with Intel Core Duo SPU @ 2.67Ghz. IE6 was tested on my machine with Virtual PC and on a PC with Windows XP SP3 and a Pentium 3 CPU 3GHz.</em></p>
<p>The results show that browsers freeze for at least 2 seconds in order to render the CSS. So it <em>is</em> possible to screw up your rendering, but you really have to make an effort for it with large HTML files and unrealistic CSS selectors.</p>
<h2>Test 2: setting up a more realistic scenario</h2>
<p>In this test I created a more realistic scenario. I took an existing CSS file and altered it until it was 113KB in size and contained about 1050 selectors. I changed the CSS rules until the bulk of the code looked like this:</p>
<pre name="code" class="css:nogutter">
.Homepage .containerText {
	position: relative;
	margin: 15px auto 0px auto;
	width: 960px;
	background:#ffffff;
}
.Homepage .containerText .containerLeft {
	float:left;
	width:450px;
	padding:10px 20px 45px 10px;
}
.Homepage .containerText .containerLeft p {
	margin:0px 0px 5px 0px;
	color:#414a49;
	line-height:1.286em;
}
</pre>
<p>So most of the code in the CSS file consisted of descendant selectors with classes and hardly any tag names. The corresponding HTML page was also created from existing code and copy-pasted until the file was 107KB in size with almost 600 opening HTML brackets (<). Now we have a relatively large HTML and CSS, but not unrealistic. Once again I tested it in different browsers:</p>
<h3>Results Test 2</h3>
<table>
<thead>
<tr>
<th>Browser</th>
<th>Render time (sec)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Firefox 3.6</td>
<td>0</td>
</tr>
<tr>
<td>IE 8</td>
<td>0</td>
</tr>
<tr>
<td>IE 7</td>
<td>0.5</td>
</tr>
<tr>
<td>IE 6</td>
<td>1.5</td>
</tr>
<tr>
<td>Chrome 6</td>
<td>0</td>
</tr>
</tbody>
</table>
<p>All modern browsers responded so fast that I couldn&#8217;t really notice it needed rendering time. This means that the CSS file does not need any optimization by utilizing ID&#8217;s. The only browser that could profit from more efficient CSS selectors is IE 6. But since I don&#8217;t have to support IE 6 anymore, it&#8217;s not worth my time.</p>
<h2>Conclusion</h2>
<p>Writing fast CSS certainly will help some browsers on slow PC&#8217;s. But that is a minority of the users. So unless you have special requirements for your website, you&#8217;ll be better off focusing on writing logical, maintainable code than trying to get the browser to render a few milliseconds faster. There are some considerations though:</p>
<h3>Being more specific</h3>
<p>A few years ago I switched from writing <code>.foo</code> to writing <code>a.foo</code>. Adding the tag name in the selector gives me a better idea <em>what</em> I&#8217;m styling. Now I know that this coding style is also faster in rendering.</p>
<h3>Descendant selectors</h3>
<p>Descendent selectors (using more than one element in a CSS rule) are inefficient in rendering, but I won&#8217;t give that up. I like to be specific about what element I want to select in CSS. I rather write <code>div.column1 div.article span.date</code> than <code>span.date</code>. The latter is more efficient, but that only works with very small websites because only then you&#8217;d still have an overview of the all classes that are in the HTML code.</p>
<p>When I write JavaScript code I try not to &#8216;pollute&#8217; the global namespace. I try to do the same with CSS by using descendent selectors.</p>
<p>If you need faster rendering, you could alter descendant selectors by making one class that incorporates the whole path. So you&#8217;ll get <code>span.column1_article_date</code> instead of <code>div.column1 div.article span.date</code>. Although it would render faster, it also has some drawbacks. Renaming a class afterwards is tedious work, the class names can become very long and the classes can be used <em>outside</em> it&#8217;s intended containers, so a class called <code>div.column1_article_date</code> could be used anywhere in the DOM and not just inside div with the class <code>column1</code>.</p>
<h2>ID&#8217;s and JavaScript</h2>
<p>I do use ID&#8217;s by the way, Not in CSS though, but for JavaScript for these reasons:</p>
<ul>
<li>Specific elements can be easily accessed in plain JavaScript with <code>getElementById</code>.</li>
<li>If an element has an ID, I can be pretty surre that there is a bit of JavaScript attached to it.</li>
<li>Using ID&#8217;s in your jQuery selectors makes the selectors less dependent on the current HTML structure. It&#8217;s easy to break existing jQuery selectors by removing a class in the DOM.</li>
</ul>


<p>Related posts:<ol><li><a href='http://www.thebrightlines.com/2009/12/24/too-advanced-css-selectors/' rel='bookmark' title='Permanent Link: Too advanced CSS selectors'>Too advanced CSS selectors</a></li>
<li><a href='http://www.thebrightlines.com/2010/01/31/hack-how-to-enable-first-child-in-ie6/' rel='bookmark' title='Permanent Link: Hack: how to enable :first-child in IE6'>Hack: how to enable :first-child in IE6</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.thebrightlines.com/2010/07/28/css-performance-who-cares/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Too advanced CSS selectors</title>
		<link>http://www.thebrightlines.com/2009/12/24/too-advanced-css-selectors/</link>
		<comments>http://www.thebrightlines.com/2009/12/24/too-advanced-css-selectors/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 22:27:05 +0000</pubDate>
		<dc:creator>Wouter Bos</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[CSS3]]></category>
		<category><![CDATA[selector]]></category>

		<guid isPermaLink="false">http://www.thebrightlines.com/?p=273</guid>
		<description><![CDATA[CSS offers lots of different selectors, but sometimes it's better not to use them.]]></description>
			<content:encoded><![CDATA[<p>A few years ago the only reasonable way to select an element through CSS was by using classes and/or tag names. If you wanted to target a specific element, you had to select it by using its classname. Selecting elements with tag names wasn&#8217;t always practicle. For example: if you use the selector <code>div.container div</code>, you style all <code>div</code> elements inside the <code>div.container</code>.</p>
<p>Most of the time that&#8217;s not what you want. Using tag names as selectors can also make design changes troublesome if you have to add more <code>div</code>s and need to give it a different styling. But since IE7 we can use new selectors that help us to build much more delicate CSS selectors. Those new selectors are:</p>
<ul>
<li>Child selector: <code>.parent &gt; .child</code></li>
<li>First child selector: <code>.parent .child:first-child</code></li>
<li>Adjacent selector: <code>.sibling + .sibling</code></li>
<li>First child selector: <code>div:first-child</code></li>
<li>Attribute selectors: <code>div[id]</code></li>
</ul>
<p>Now you can style the following HTML with just a single class:</p>
<h3>HTML:</h3>
<pre name="code" class="xhtml:nogutter">
<div class='container'>
	<span>This is some title</span>
	<a href="#">Lorem ipsum</a>
	<a href="#">Lorem ipsum</a>
	<a href="#">Lorem ipsum</a>
	<span>Some body text with lots of <span>lorem <span>ipsums</span></span> in it</span>
	<span>Some body text with lots of <span>lorem <span>ipsums</span></span> in it</span>
	<a href="#">Lorem ipsum</a>
</div>
</pre>
<h3>CSS:</h3>
<pre name="code" class="css:nogutter">
.container span {
	font-family: sans-serif;
}
.container > span:first-child {
	font-size: 1.5em;
	font-weight: bold;
	font-family: serif;
}
.container > span > span {
	font-style: italic;
}
.container > span > span > span {
	font-weight: bold;
}
.container > span + span {
	display: block;
	margin-top: 0.5em;
}
.container a:nth-child(2) {
	font-weight: bold;
}
.container a {
	display: block;
	color: #f0f;
}
.container a:nth-child(4) ~ a {
	font-size: 0.9em;
}
</pre>
<p>The advantage is that you can, as you can see, style whole blocks of HTML code with just one class. In theory you could even use no classes at all. Without &#8216;class&#8217;-attributes on every element, the HTML code looks just a little bit more cleaner and readable. You can also use those and other selectors in javascript libraries like jQuery to select particular HTML elements. Since most libraries are cross-browser you don&#8217;t have to worry if a selector is or isn&#8217;t supported by a browser. Consider this piece of code in jQuery:</p>
<pre name="code" class="javascript:nogutter">
jQuery(".container a:nth-child(4) ~ a").click( function() {
	alert('hello world');
})
</pre>
<h2>That&#8217;s all nice, but should I use it?</h2>
<p>No. I use them some times, but I try to stay away from it if possible. The problem with these selectors is that they rely so much on the structure of the HTML that it becomes harder to change the HTML structure. If you take another look at the HTML and CSS that I showed as an example in the beginning of the article, it&#8217;s clear that you can&#8217;t add a few links or spans without having to change the CSS. Add some advanced jQuery selectors in the mix and you may have locked the HTML structure forever since no-one dares to change it.</p>
<h2>Should I discard those new selectors then?</h2>
<p>Not necessarily. Sometimes you just have no choice if you for some reason are not able to change the HTML. My personal guideline is that styling has to be predictable. So when you edit some piece of HTML code, the styling should behave as expected. That means that you don&#8217;t style your HTML in a way that the text-color of the 4th <code>span</code> is red.</p>
<p>So what can be styled predictable? If you ask me advanced selectors shine when the structure is relatively fixed. Lists are a good example. Just take a look at these code blocks below. The styling will behave normal, regardless what you do with the HTML.</p>
<h3>HTML:</h3>
<pre name="code" class="xhtml:nogutter">
<ul class="list">
<li>Lorem</li>
<li>Ipsum</li>
<li>Dolor
<ul>
<li>Sit</li>
<li>Amet</li>
</ul>
</ul>
</pre>
<h3>CSS:</h3>
<pre name="code" class="css:nogutter">
ul.list li + li {
	margin-top: 10px; /* adds top margin to all list items except the first */
}
ul.list > li {
	font-weight: bold; /* styles only the first level list items differently */
}
</pre>
<h3>Javascript:</h3>
<pre name="code" class="javascript:nogutter">
jQuery("ul.list li:nth-child(even)").addClass("zebra"); // adds zebra striping to a list
</pre>
<h2>HTML elements you can easily apply advanced selectors</h2>
<p>Besides <code>ul</code>, you can style <code>ul</code>s, <code>dl</code>s, <code>table</code>s. That doesn&#8217;t mean that other elements should only be styled with classes. There are always some exceptions to the rule. Just let your common sense be the judge.</p>


<p>Related posts:<ol><li><a href='http://www.thebrightlines.com/2009/11/08/how-to-overcome-the-limits-of-css-in-internet-explorer-6/' rel='bookmark' title='Permanent Link: How to overcome the limits of CSS in Internet Explorer 6'>How to overcome the limits of CSS in Internet Explorer 6</a></li>
<li><a href='http://www.thebrightlines.com/2009/10/28/for-the-sloppy-clickers/' rel='bookmark' title='Permanent Link: For the sloppy clickers'>For the sloppy clickers</a></li>
<li><a href='http://www.thebrightlines.com/2010/01/31/hack-how-to-enable-first-child-in-ie6/' rel='bookmark' title='Permanent Link: Hack: how to enable :first-child in IE6'>Hack: how to enable :first-child in IE6</a></li>
<li><a href='http://www.thebrightlines.com/2010/01/04/alternative-for-nth-of-type-and-nth-child/' rel='bookmark' title='Permanent Link: Alternative for :nth-of-type() and :nth-child()'>Alternative for :nth-of-type() and :nth-child()</a></li>
<li><a href='http://www.thebrightlines.com/2009/11/27/filtering-ie6-and-ie7-in-quirks-mode/' rel='bookmark' title='Permanent Link: What you can&#8217;t do in IE&#8217;s Quirks Mode'>What you can&#8217;t do in IE&#8217;s Quirks Mode</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.thebrightlines.com/2009/12/24/too-advanced-css-selectors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

