Faster CSS

Sitepoint Members,

In an older thread Noonnope wrote:

"In order to apply CSS style, a CSS rule (the selector part) is evaluated by the browser, from right to left, in order to identify the elements in the created DOM, based on the HTML markup.

For div.firstimg{…}, the browser must:

  • first identify which elements have the class=“firstimg” values
  • then filter only the div tags from its findings

Obviously, .firstimg{…} it’s a one step:

  • identify which elements have the class=‘firstimg’ values. "

Is it true that for a css command such as #firstimg the browser has to

  • first identify which elements have the class=“firstimg” values
  • then filter only the id tags from its findings ?

If so then processing #firstimg is more work and more time for the browser than .firstimg.

Thanks,

Chris

You are missing one concept here.

div.firstimg{} targets only DIVs with class=" firstimg", .firstimg{} targets ANY ELEMENT with class=" firstimg". Yes, div.firstimg{} takes more effort for the browser… BUT ITS ALSO MORE SPECIFIC.

Is it true that for a css command such as #firstimg the browser has to

  • first identify which elements have the class=“firstimg” values
  • then filter only the id tags from its findings ?

This would indicate you have an element such as <p id=“firstimg” class=“firstimg”> which begs the question … WHY? but yes, if you do this the browser would have to follow the above method, otherwise it goes straight for the ID.

The real rule is use IDs ONLY when they are unique. At that point adding classes to an ID element is… ok, but redundant since you can easily declare any rules in the CSS

for example:
#firstimg{border:1px solid #000;}
.myclass{padding:5px; background: pink;}

<div id=“firstimg” class=“myclass”></div>
<p class=“myclass”></p>

could be optimized as:

#firstimg{border:1px solid #000;}
.myclass, #firstimg{padding:5px; background: pink;}

<div id=“firstimg” ></div>
<p class=“myclass”></p>

Dresden_Phoenix,
what I have is
Content{position:relative;float:left;width:100%;overflow:hidden;background-color:#3F3F7F;border-bottom:1.5em solid #9F9FFF;padding:10px 0}
#colmid{float:left;width:200%;margin-left:-160px;position:relative;right:100%}
#colleft{float:left;width:100%;margin-left:-50%;position:relative;left:320px}
(and 5 more like these)
They set up the structure of my site.

I’m considering changing them to
.content …
.colmid …
.colleft …

and then changing the html to match. The reason is to get the code to run as fast as posible. If this changre saves 8 passes, it’s worth my time to make the change. I just don’t see how the computers and software that interpret the code are helped by declaring that a pasrticular line of code is unique. I don’t see the same declaration of uniqueness availability in HTML, PHP.

Thanks,

Chris

I am not certain. It doesn’t make sense that an element would look for classes of an ID as ID and classes are UNRELATED. But I will defer to someone with more expertize on UA behavior, which could even mean that this varies by vendor!

Ok, this falls into the “say what?” area – as if your code is complex enough you even have to worry about the difference between and ID and a Class, there is something HORRENDOUSLY WRONG with your page!!!

It’s like the people who talk about “tables taking longer to load” (when they mean longer to render) – if a 40mhz 386 running windows 3.1 and IE4 can handle a table? That’s a pointless thing to be worried about when your average SMARTPHONE has a 700mhz or faster ARM9 in it.

If you’re looking for speed optimizations, look somewhere else – SERIOUSLY. What’s your CTC (Code to Content) ratio on the markup? (more than 3:1 is complete rubbish, more than 2:1 usually indicates bad coding practices!) How big is your total CSS? (if it’s more than 32k, you’ve probably screwed up)… how many separate image and scripting files are you loading? (handshaking being the biggest bottleneck on most sites!). Are you layering multiple backgrounds or effects with CSS3? (brings firefox to it’s knees)… etc, etc, etc…

Do you have a sample of the code you are trying to optimize and/or an example page? Speeding up websites is my specialty and usually when people start resorting to things like this, or idiocy like white-space stripping (aka minification) the problems actually lie elsewhere – like hundreds of K of javascript, endless wrapping div for no good reason, and dozens of unnecessary classes resulting in 100k of HTML to deliver 4k of plaintext and five content images…

While it’s good to see someone concerned with their page loading and rendering times, yer looking in the wrong place.

Of course with the needlessly cryptic and semi-presentational ID names, it doesn’t bode well for the rest of the markup. (I could be wrong though – it’s just a feeling).

deathshadow60,

How about this question:

Which is less work for a browser
Content{…
or
.content{…

Both work on my site.

Thanks,

Chris

Honestly it should be no more or less work – Id’s are processed AFTER classes though, but in terms of their being applied it should hinge on the browser. Does the browser build a list of ID’s and classes on elements BEFORE it applies CSS (Webkit, Opera) or does it parse through the DOM on every pass (IE :sunglasses: or a hybrid of the two (Gecko). How many classes are declared in the document? How many Id’s? How many elements on the page?

In terms of how long it should take either way – unless you have THOUSANDS of DOM elements it should be so fast it shouldn’t matter on any computer faster than 40mhz.

Use ID’s for when the element is unique, or you want to target it with a hash (#) or by javascript – use classes when you are going to have more than one of them, and even then do so sparingly and use the actual element structures via semantics instead… and don’t sweat how long it takes for the renderer to factor them in.

It’s a nonsensical question with no clear answer; the answer in fact being different not just by browser, but by the page it’s on.

Which is why actually seeing your site if you are in fact having speed issues would probably get you more meaningful answers… than worrying about something that should take so little time as to be a non-event.

… and that’s coming from someone who usually DOES obsess on the little stuff.

Hi,

You can find some more information [URL=“https://developer.mozilla.org/en/Writing_Efficient_CSS”]here and [URL=“http://www.stevesouders.com/blog/2009/06/18/simplifying-css-selectors/”]here but as Jason said this is probably the last place you should be looking if to make speed improvements.

How about this question:

Which is less work for a browser
Content{…
or
.content{…

In theory they should be much the same because matching from right to left both are matched immediately and then put into a hash table of some sort and the browser moves on with the next task. David Baron goes into some detail in this rather stuttering video.

More info.

Performance impact of css selectors
Efficient CSS

The end of the article Paul O’ B linked to Efficient CSS puts it perfectly:

So we know that ID’s are the most efficient selectors. If you wanted to make the most efficiently rendering page possible, you would literally give every single element on the page a unique ID, then apply styling with single ID selectors. That would be super fast, and also super ridiculous. It would probably be extremely non-semantic and extremely difficult to maintain. You don’t see this approach even on hardcore performance based sites. I think the lesson here is not to sacrifice semantics or maintainability for efficient CSS.

As deathshadow60 mentioned one of the key ingredients to client-side optimization is aggregation of external resources – limiting the number of outbound requests for external assets. That is where a majority of any type of client-side bottleneck will lye.

That 'tis a good quote. Like anything else it’s a balancing act – you concentrate too hard on any one thing, you’re likely sacrificing elsewhere.

Like if when they built the DOM inside the browsers they recorded the classes, tags and ID’s into a Btree type structure. Would speed up rendering of CSS astronomically – and chew on RAM like a five year old with a Pez dispenser. It would make MORE sense to parse left to right, since that would narrow the targets of each search instead of narrowing it… but that would involve maintaining a larger tree going down… and again more RAM consumption.

Browser makers agonize over these types of compromises so we don’t have to… which is why if I was looking to speed up a page, worrying about how selectors resolve is pretty much not even on my list. Swinging a giant axe at bloated scripts, reducing the number of files used to build the page, ditching anything that has the word “framework” involved with it, reducing the number of DOM elements on the page, and avoiding slow to draw properties topping my list of optimizations.

Heck, those selectors being slow – directly related to the number of DOM elements on the page! Less DOM elements (tags) you use, the less the CSS has to sort through when APPLYING that style. It’s why I keep pointing out in people’s code when they nest tags endlessly (deeper DOM tree slower to parse), or use extra wrapping div like <div id=“header”> or <div id=“nav”> around perfectly good existing semantic tags (like H1 and UL)… and a hefty contributor to why I think a LOT of the new HTML 5 tags are just pointless bloat. Removing just one element from the DOM means EVERY CSS property is just that much faster.

DS60

What are some common strategies for reducing the number of DOM elements on a page?

What is “avoiding slow to draw properties”

Thanks for the tips,

Chris

Don’t slap a div around a block level container until you HAVE to – for example, you’ll see code like this all the time:


	<div id="header">
		<h1>Some title</h1>
		<div id="nav">
			<ul id="navUL">
				<li class="navLI">
					<a href="#" class="navA">Menu item</a>
				</li>
			</ul>
		</div>
	</div>

When on 99% of layouts there is no need for #header, no need for #nav… that’s two excess DOM elements as H1 and UL are perfectly good block level containers all on their own.

It ALSO introduces extra ID’s and classes – if those elements LACKED classes/id’s it’s easier for the browser to go “ok this is empty” instead of “does this match”.

Which is why on the majority of websites there is little reason for that same code to be much more than:


	<h1>Some Title</h1>
	<ul id="mainMenu">
		<li>
			<a href="#">Menu Item</a>
		</ul>
	</ul>

See part of why I call turdpress… well… turdpress given what it typically vomits up for markup – ESPECIALLY in regards to classes. Stacked presentational classes? PLEASE.

There’s this… tendency many developers have to just slap div after div after div in their code… Tables for layout and tables for nothing are similarly afflicted in terms of ‘extra’ elements… You’ll also occasionally see this:


<div id="someData">
	<h2>Data Title</h2>
	<table id="someDataTable">
		<tr>
			<td class="empty">&nbsp;</td>
			<td class="colHeading"><strong>Column 1</strong></td>
			<td class="colHeading"><strong>Column 2</strong></td>
			<td class="colHeading"><strong>Column 2</strong></td>
		</tr><tr>
			<td class="rowHeading"><strong>Row 1</strong></td>
			<td class="rowData">1-1</td>
			<td class="rowData">1-2</td>
			<td class="rowData">1-3</td>
		</tr><tr>
			<td class="rowHeading"><strong>Row 2</strong></td>
			<td class="rowData">2-1</td>
			<td class="rowData">2-2</td>
			<td class="rowData">2-3</td>
		</tr><tr>
			<td class="rowHeading"><strong>Row 3</strong></td>
			<td class="rowData">3-1</td>
			<td class="rowData">3-2</td>
			<td class="rowData">3-3</td>
		</tr>
	</table>
</div>

The H2 should be a caption, meaning it doesn’t need the div… the first TR should be inside THEAD with TH instead of strong, the empty one doesn’t need &nbsp (a textnode in the DOM) if you use empty-cells:show; and could be targeted as the only TD in thead… the td.rowheading should also be TH, removing more unneccesary STRONG tags.

You count that out, it’s 29 DOM elements (not counting textnodes), 16 class instances and two id’s that need to be processed! You’ll see tables like that all the time – and it’s just bloat because people didn’t learn about CAPTION, THEAD, TBODY or TH.


<table id="someData">
	<caption>Data Title</caption>
	<thead>
		<tr>
			<td></td>
			<th>Column 1</th>
			<th>Column 2</th>
			<th>Column 3</th>
		</tr>
	</thead><tbody>
		<tr>
			<th>Row 1</th>
			<td>1-1</td>
			<td>1-2</td>
			<td>1-3</td>
		</tr><tr>
			<th>Row 2</th>
			<td>2-1</td>
			<td>2-2</td>
			<td>2-3</td>
		</tr><tr>
			<th>Row 3</th>
			<td>3-1</td>
			<td>3-2</td>
			<td>3-3</td>
		</tr>
	</tbody>
</table>

The difference? 24 tags, one ID and no classes needed! It’s also less code in the HTML meaning the DOM can be built faster… literally we’re talking 847 bytes vs. 450…

alpha transparent images, very small palette transparent images when tiled both directions, multiple layered CSS3 backgrounds (see that cicada background train wreck – looks great until you try to SCROLL), anything with position:fixed – these can drag some browsers to their knees. Any image that decodes to more than 0.25 megapixels…

header is a perfectly fine contextual grouping of related elements imo.

Yep, and your web pages would look as good as deathshadow60’s…

It all comes down to the right balance – no transparent images give me a break…

DS60, Oddz,
the only thing I have close to #header is
.header{display:block;margin-left:auto;margin-right:auto;background-image:url(/aa.jpg);width:808px;height:123px}

of course if the jpg would load faster with #header, I would use
it. The jpg is for the image I have at the top of each page.

Are there any tools you know of that analyze DOMs?

Thanks,

Chris

WHICH AGAIN without seeing the actual page it’s on, ANYTHING we tell you is nothing more than a wild guess! That said the fixed width and presence of such a declaration PROBABLY means you have unneccesary elements in your HTML… but let me just broken record that – without seeing actual code preferably as a live page…

Hell, just the white space stripping and shoving it all on one line doesn’t bode well – nor does the lack of condensed properties (like say that anchor).

Firebug… Dragonfly…

Something you learn in software engineering that over-optimization is worse than no optimization. Only optimize something that is causing a significant bottle neck (that isn’t saying to write crappy code, just don’t spend 6 hours trying to save 2 seconds).

Really the only websites that should be worrying about these type of things are sites like Facebook and Google which have thousands of hits a minute. For any other site, you aren’t going to cause it to load any measurable amount faster (if it is, you’re code is probably crummy and as DS said, there are other places to optimize).

Which if you take the time to view source, you realize they don’t. (google’s getting REALLY bad in fact)… Google for example could stop stripping out all their whitespace and probably STILL cut their bandwidth use in half by just moving all the static crap that isn’t HTML… out of their HTML.

Your extra bit in parenthesis is the part of that saying many people miss. They seem to use the “over-optimization is worse than no optimization” as an excuse for their lazy-ass garbage code.

There are coding practices that take little to no extra effort that may in fact add up to bloat – formatting with tabs and extra carriage returns for example. They make the parser take a bit longer, but it’s worth it just from a maintainability standpoint. Learning to rigidly follow a formatting standard can prevent you from making mistakes in the first place – mistakes you could waste hours on trying to find when you could have just spent an extra minute over K-LoC hitting tab, shift-tab, backspace and enter few dozen more times. If that extra quarter k of characters is actually significant enough to have an impact on your bandwidth, there’s likely something horrendously wrong with how it’s coded in the first place.

Which is why I usually call BS on white space stripping/minification… Most of the time it’s used to cover up garbage code instead of taking the time to FIX garbage code.

Not using CSS to it’s full capacity just because you’re worried about the performance of selectors… falls into that same category. The browsers ability to actually render a page still outpaces the bandwidth by a factor of a thousand to one – and until we’re all sitting on 1tbps connections with servers connected to 10ptbs pipes, worrying about the speed of something as simple as dom applications of properties is kinda silly.

Especially compared to the times of DOM manipulation, actually RENDERING the styles, and of course, how big the page is, how many separate files it’s made out of, and how well you leverage the browser caching models.

Agreed (even though I still minify ;)).

I do have a question and this is out of curiosity. I tend to try to avoid ID’s and classes whenever a I can and instead use siblings or descendants or attribute matching to do my styling.

I assume that div p em {…styling goes here…} is better than em.className {…styling goes here…} ?

@molona – While speed wise there’s probably no difference – less classes means less CODE in the markup – less HTML, even at the cost of more CSS is usually a good thing since CSS in an external file can be shared and therein cached across pages on a site, while HTML is obviously not.

So using semantic tags instead of classes on everything? Good thing. REALLY GOOD THING. It’s part of the reason to even practice semantic coding in the first place. Part of what I meant up above with those examples having classes on everything for no good reason.