29

As a web developer, you can only go to a certain amount of effort to optimize your CSS code. However, computers can take into account way more in almost no time and are thus better in optimizing. The question is: What CSS code is hypothetically the most optimized? (for modern browsers)

Considering the following image: enter image description here

A, B, C and D are DOM-objects (lets say DIV-elements) and the numbers 1-17 represent attributes (like color, background, width, height, etc)

Whereas all numbers represent a unique attributes. e.g:

4 = background-color: #FF0;    
5 = width: 50px;
10 = background-color: #F00;

There are multiple ways you can generate the css code for this web:

All own ID's

#A { 1 2 5 8 9 10 12 }
#B { 1 4 5 11 12 13 14 15 }
#C { 1 2 3 5 7 }
#D { 3 4 5 6 16 17 }

However, the file would be very large, the attributes are not shared and a simple test proofs that this is rather slow to render. (image1.html, see file generating script below)

Share some common attributes

#A { 2 8 9 10 12 }
#B { 4 11 12 13 14 15 }
#C { 2 3 7 }
#D { 3 4 6 16 17 }
.1 { 1 }
.5 { 5 }

The file would be smaller and the rendering seems to be quicker. (see image2.html)

Share ALL common attributes

#A { 8 9 10 }
#B { 11 13 14 15 }
#C { 7 }
#D { 6 16 17 }
.1 { 1 }
.3 { 3 }
.2 { 2 }
.4 { 4 }
.5 { 5 }
.12 { 12 }

The file would be even smaller (most of the time) and as it turns out the rendering goes quicker as well. But notice that A, B and C end up with one ID, and 4 classes that contain only one attribute! (see image3.html)

Now these are three simple examples of CSS code. But as you can imagion, when more DOM objects exist, and more overlap of attributes exist, you could theoretically end up with one DOM object with 1 ID and 10'ths of classes!

What CSS code is hypothetically the most optimized? (for modern browsers) Should you limit the amount of classess per DOM object? should you prefer a "single attribute containing class" over adding it to an ID?

p.s. as a test I loaded an image using PHP. Than read the pixel value of that PNG and create the same picture using CSS and DIV-elements. The code for generating image1.html, image2.html and image3.html can be found here You can use ANY PNG image... I used this image

14
  • 2
    It has nothing to do with individual taste, since I'm not asking for an opinion but fact based evidence for the most optimized css code. Now this might indeed differ slightly amonst browsers, yet there will most certainly be some agreement Commented Sep 26, 2015 at 13:30
  • 2
    @Jeffrey I don't get your question: you were able to find out that the "share all common attributes" generates the smallest file and is the fastest solution. Then it seems that you think that "A, B and C end up with one ID, and 4 classes that contain only one attribute! " is a minus point for this solution. This is to me a good thing not a bad one.. why are you trying to say that this should be a problem? Commented Oct 5, 2015 at 13:39
  • 10
    Define "optimized". Smallest code? Fastest parsing time? Easiest to write? Easiest to maintain? Fasted to apply at run-time? The general rule for all optimization problems is that you first optimize for clarity and correctness. Then, if you find you have a performance problem in a particular area, you optimize for it. Except in huge websites with thousands of elements and extremely complex rules, I've seen very few cases where CSS is the optimization priority. So I don't think this is an important problem, except if it's an academic exercise. Commented Oct 5, 2015 at 14:05
  • 6
    So it's parse time, as opposed to the time to apply the rules at run-time, that you want to prioritize? A simplistic approximation would be that parse time is linear in length, meaning that whatever approach compresses/factors/combines rules best would "win". However, such an approach would likely be slower at run time. You have to decide what your priority is. Actually, as I mentioned neither parse time nor apply time is likely to be a good top priority. Commented Oct 5, 2015 at 14:17
  • 3
    See developer.mozilla.org/en-US/docs/Web/Guide/CSS/…. Commented Oct 5, 2015 at 16:01

3 Answers 3

7

you have already answered your own question with the test you created.

@torazaburo has provided good input for your question.

creating IDs and Classes for every shared attribute will speed up your runtime. on the other hand created classes containing the most attributes will speed up parse time. the problem with both approaches is that if you use this as a rule of thumb, your code will quickly become unreadable and complex to maintain.

this is where your own judgement and work style comes into place. I don't see a point for creating IDs or Classes for single attributes or Classes for elements that are not repetitive in your DOM, as the load time gain you will experience will be insignificant.

therefore, try to prioritise your CSS optimisation by solving code duplication issues. this will effectively reduce your overall load times and make your code readable and maintainable for the future.

Sign up to request clarification or add additional context in comments.

4 Comments

In the OP's definition of optimization, "user maintainability and readability are not important at all." It appears they are creating a fully generated CSS file on the server that will not be maintained by themselves or other developers. It's an academic question about computational idealism with no basis in human pragmatism.
@gfullam in that case, the answer is still present in the original post
Perhaps. But that is just empirical evidence. The OP is "looking for an answer drawing from credible and/or official sources."
Many questions are still left unknown, for which i'm looking for an answear. see the 'subquestions' in the post, as well as the subquestions in the comments I placed below
2
+100

Browsers should be doing any such optimization internally, as they “compile” the CSS. The compiler is responsible for optimization, because it knows about its implementation details and is able to tell, which fits its needs best.

Programmers can take care only of the things that the compiler is unable to deduce (e.g. due to being unable to solve the halting problem). Otherwise, writing semantically correct code is their best bet.

This is actually in accordance with what Antti Koivisto, a contributor to WebKit core, said in 2011, having spent some time optimizing its CSS selector matching:

My view is that authors should not need to worry about optimizing selectors (and from what I see, they generally don’t), that should be the job of the engine.

Quote via CSS Selector Performance has changed! (For the better) by Nicole Sullivan. A good source about modern-day CSS optimization, BTW. The article is referenced in the note at the top of the outdated 2000 article Writing efficient CSS by David Hyatt.

So the concern about premature optimization expressed by some commenters and shared by me is probably warranted.

2 Comments

With the bounty due in less than an hour, this is the best answer so far. You have a point, saying that it is the task of the engine to make the rendering as fast as possible, and not the user. Taking into account the link (also provided by torazaburo), it is clear that the correct use of selectors will be of great importance to the speed. To me, one important question is left; is there a limit on amount of selectors to one DOM object before it slows down the process?
From what I know, the main problem is telling the selectors that match from those that do not. If a selector actually matches, it needs to be examined in its entirety, therefore the overall complexity depends on the complexity of used selectors. (The linked article says adjacency combinators can still be slow.) Moreover, when the selector matches, the associated declarations have to be applied. I’m not sure about the complexity of this step, e.g. because specificity calculation is involved. I guess the overall complexity is proportional to the number of declarations being applied.
0

One setback I'm thinking of is responsive capability. Let's take for example this code:

HTML:

<ul class="overflowHidden blackOnePixelBorder resetPadddingAndMargin noListStyle">
    <li class="backgroundGreen floatLeft threePerRow heightTwoHunderPixels"></li>
    <li class="backgroundRed floatLeft threePerRow heightTwoHunderPixels"></li>
    <li class="backgroundBlue floatLeft threePerRow heightTwoHunderPixels"></li>
    <li class="backgroundRed floatLeft threePerRow heightTwoHunderPixels"></li>
    <li class="backgroundBlue floatLeft threePerRow heightTwoHunderPixels"></li>
    <li class="backgroundGreen floatLeft threePerRow heightTwoHunderPixels"></li>
</ul>

CSS:

.resetPadddingAndMargin {
    padding: 0;
    margin: 0;
}
.noListStyle {
    list-style: none;
}
.overflowHidden {
    overflow: hidden;
}
.blackOnePixelBorder {
    border: 1px solid #000;
}
.backgroundRed {
    background: #f00;
}
.backgroundGreen {
    background: #0f0;
}
.backgroundBlue {
    background: #00f;
}
.floatLeft {
    float: left;
}
.threePerRow {
    width: 33.33%;
}
.heightTwoHunderPixels {
    height: 200px;
}

http://jsfiddle.net/bqh8he7e/

How are you gonna resolve the problem of overlapping CSS code or if you want to use one class in different resolutions or devices without overwriting it when you want to have all the squares on one line ? (*without JS)

(I hope I understood your idea)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.