CSS: Duplicate Selectors vs. Duplicate Declarations - css

Which CSS authoring technique do rendering engines process more efficiently:
1) repeating the same style property/value pair in multiple selectors, or
2) grouping shared style properties in a single selector
Example 1: Duplicate font-size, but less rules
p {
font-size: 1em;
color: #000;
}
h1 {
font-size: 1em;
color: #fff;
}
or Example 2: More rules but one font-size
p, h1 {
font-size: 1em;
}
p {
color: #000;
}
h1 {
color: #fff;
}

This study by Dave Gregory is the best source I've found on this topic. It shows that duplicating property/value pairs is much worse for performance:
"Long" is what Gregory refers to as the "bloated" format where properties are repeated in multiple selectors.

for performance is better the second option, see this google advice, but take care of using declarations in just one place, you could finish with something like this, this is the problem with extend in css preprocessor like sass and stylus. However your first option could be more modular and makes your css modules more independent and reusable in other sites, you can then make use of a css minifier to group every declaration.

Organizing your css is really up to you and the number of elements you have.
If you are looking for optimization you should instead focus on useless whitespaces and duplicates.
Tools exist to merge the duplicates and minimize your code (here and here for example)
You may also read this article which is a bit old but still valuable I think.

Related

Grid-Media IN vs OUT

Me and a coworker went into an eternal discussion about what is the best way to use Neat Grid-Medias.
Consider the following approuch:
Approuch A:
.mydiv {
font-size: 14px;
#include grid-media($somegridvar) {
font-size: 18px;
}
}
Then, consider this:
Approuch B:
.mydiv {
font-size: 14px;
}
#include grid-media($somegridvar) {
.mydiv {
font-size: 18px;
}
}
Testing on Neat, both approuchs renders to the same result, which i will not put here because its obvious.
My question is: What do you prefer?
There is a "better" approach suggested by ThoughtBot?
There is a "better" approach suggested by someone?
There is a reason to use one instead of other?
Its just a matter of style?
Someone have use both to provide an enriched life statement?
What we deduced till now:
In Approuch A, we will have several includes of Grid Media on our pages, making the code harder to read and more bloated.
At the other side, all Grid Media will be centered in one single rule, and the same rule will not be repeated over the document for each Grid Media.
In Approuch B, we will have a single block of each grid-media for each breakpoint, resulting in a much shorter code, but also multiplying the places where the element classes appear.
Also, if this coworker is reading this, im looking forward to discover that my way was the better. (yes, i will not tell you which one)
👋 Hi!
I’ll preface this by saying that code style is a team thing. What works for us, may not work for you. Above all, consistency and a shared understanding is really what matters. Don’t spend too much time in the weeds, little details. That being said, we (thoughtbot) publish our code style guides and prefer this syntax (your ‘Approach A’):
.mydiv {
font-size: 14px;
#include grid-media($somegridvar) {
font-size: 18px;
}
}
Why? mydiv is the thing you’re styling, not the media query itself. So encompassing all styles that relate to that selector within one declaration block provides a lot of clarity. Having styles that affect the selector spread out through multiple blocks can become hard to decipher.

Make LESS remove useless IDs when compiling

One feature I really love with LESS is nested rules. It makes the stylesheet much cleaner that way and you can find an element very quickly.
I was wondering if there's an option when compiling to optimize selectors. For example...
#global {
/* Styles here maybe */
.container {
/* Styles here maybe */
#sidebar {
/* Styles here maybe */
.title {
font-weight: bold;
}
}
}
}
will be compiled to #global .container #sidebar .title { font-weight: bold; }.
But the first two selectors are useless, since #sidebar should be unique in my page.
Is there a way to ask LESS to compile this to #sidebar .title { font-weight: bold; } instead?
Your assumption is wrong that multiple IDs in CSS are redundant. Imagine, as an example, a site where the CMS generates the page type into the output, like that it's the contact page:
<body id="contact">
<section id="content">Blah</section>
</body>
According to your logic, the following piece of CSS would be a candidate for 'optimization':
#contact #content {
background:red;
}
Now however, your home page has <body id="home"> of course in this imaginary CMS. And suddenly the content of your homepage has a red background because you decided to erroneously optimize that #contact selector out of the CSS, while it most certainly shouldn't have a red background according to this rule.
So no, LESS cannot do this because it would break code. If you don't want the selectors, don't use them and don't put them in your code.
Other answers, including the accepted one, have explained convincingly why LESS cannot simplify your nested selectors in the way you want.
Actually, SASS has the ability to do this:
#global {
.container {
#at-root #sidebar {
.title {
font-weight: bold;
The #at-root directive essentially ignores all the higher nesting selectors. I don't know if LESS has something similar. The above compiles into simply
#sidebar {
.title {
font-weight: bold;
But there is a deeper issue here, starting with the fact that you "love" nested rules in LESS. Stop loving them quite so much. I don't know about you, but most people love nested rules because they think it's cool to exactly mimic the hierarchical structure of their HTML. The SASS docs even claim this as a benefit:
Sass will let you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML.
So people with HTML such as
<div class="foo">
<ul>
<li class="item">
write LESS like
.foo {
ul {
li.item {
This is a horrible, horrible idea, It makes the structure of CSS completely dependent on the structure of the HTML. If you change one nesting level in the HTML, your CSS breaks. Often this approach is combined with a lot of rules defined against tag names such as ul instead of class names, which aggravates the dependency, so changing the ul to ol in the HTML breaks the rules again. Or it's combined with rules based on Bootstrap classes such as col-md-6, so if you ever change that to col-md-4 things break again.
CSS rules should be orthogonal to the HTML. They represent a different dimension. They represent styling concepts which are applied selectively throughout and across the HTML.
I am guessing that you wrote
#global {
.container {
#sidebar {
.title {
font-weight: bold;
because you are adopting this mistaken idea of mirroring the HTML structure in your LESS. Then, you notice that this compiles down to having selectors which contain multiple IDs, which you imagine must be inefficient (although, actually, the degree of inefficiency is minimal). You yourself are writing extraneous nesting levels in your LESS, then complaining that they may be slowing down performance!
Worse, you've hard-wired assumptions about the HTML structure into your CSS. It's of no consequence that the sidebar happens to fall inside a .container which is inside a global element. So don't write them. Perhaps at some point you decide to change the container class to container-fluid. Boom, instantly your CSS breaks. What is the point of conditionalizing the fact that the title should be bold on it being contained with a container class, which in any case is a layout-related class that has (or should have) nothing to do with styling? If you're going to duplicate your HTML structure in your CSS using preprocessor nesting, just go back to writing inline styles. At least that way you'll only have one file to change when you change your HTML around.
When designing CSS, you should think just as hard about the design of the rules as you do about the design of classes and methods when writing JS. In this case, you need to ask yourself, "What characterizes the situation where I want some title to be bold? What drives that? What is the nature of boldness? What am I indicating by boldness? What is the semantic notion indicated by boldness?"
Let's say that you want all titles to be bold. Then you simply say that:
.title { font-weight: bold }
Let's say that you want a title to be bold only when it's in the sidebar. Then you simply say that:
#sidebar .title { font-weight: bold; }
My suggestion here is to go cold turkey. Stop using nesting during a withdrawal period. Write rules with the minimum number of selector components. Refactor your classes to have semantic names (such as title-emphasis). Once you're "sober", you can go back to cautiously using LESS's nesting capability when it is useful, such as perhaps for hover:
#boo {
color: red;
&:hover {
color: blue;
}
}
This is actually useful and saves you from writing #boo twice, and groups the rules in an easy-to-understand way.

Are there speed benefits of putting CSS attributes in alphabetical order?

I hope this question isn't too weird and arbitrary. When I'm viewing some CSS using Firebug, I've noticed that the CSS properties for each tag are in alphabetical order.
Is it trying to tell us something?
Apart from the obvious benefit of being able to find the property you're after more quickly, I was wondering this: Is it quicker for a browser to apply the properties if they are in alphabetical order in the original stylesheet?
For example is this...
body {
background: #222;
color: #DDD;
font-size: 0.85em;
}
#content {
background: #444;
padding: 1em;
}
p {
border-bottom: 0.9em;
line-height: 1.2em;
text-align: justify;
}
...better than this...?
body {
font-size: 0.85em;
background: #222;
color: #DDD;
}
#content {
padding: 1em;
background: #444;
}
p {
text-align: justify;
line-height: 1.2em;
border-bottom: 0.9em;
}
Can this be tested effectively?
This would obviously be replicated throughout the entire stylesheet so would a browser benefit from doing things in order and, if so, would it be worth revisiting past stylesheets to reorder things?
-- edit --
Ok, a slight alteration to my question: What if the attributes are always in the same order for each tag. Background always before border always before color etc and so on (I know I've missed some!) for each and every tag. Alphabetical would aid you in keeping things in order rather than being the optimal method.
Looks like the overwhelming consensus is that it matters not, however!
There's definitely no speed benefit in ordering your styles alphabetically.
If you want real speed benefits, you should minify your CSS.
There are so many programs to do that, but here's one of them: CSSTidy. This program also has the option to put your styles in alphabetical order (if you want that for your benefit).
I don't think order of statements affects speed in any way, however, the efficiency of the statements can affect performance. (Slightly tangential, I guess...)
See: http://code.google.com/speed/page-speed/docs/rendering.html#UseEfficientCSSSelectors
The performance benefit is for visual parsing only - FireBug will re-arrange your style attributes into alphabetical order when you inspect an element, which I find much quicker to locate a style attribute.
Firebug do it so that developers can search for an attribute value easily, and if you want speed benefit, write your css judiciously, which includes mainly avoiding repetition and redundancy and being DRY
Also when a page loads and CSS is parsed and layout is rendered once, next time its not done again, so stay calm, and try to make it more maintainable instead
Writing CSS in an alphabetical order just makes one thing easy: finding your attribute. It has nothing to do with speed.
To Increase speed, you can use shorthands rather than using separate attributes. Things like border-color, border-width, border-style can be used in a single attribute called border.

With CSS, how to style a generic, global style?

Update: this question is about global style. So solution such as #some-id .score is NOT a solution.
At first, I was styling as
.score { font-size: 32px; color: #777 }
And the "score" is something that can happen any where, something of a global style. But since other style actually might have:
#summary-panel { font-size: 13px }
The one with id will override the one just having classes (the first CSS rule in this post). (So if score is displayed within summary-panel then the font-size will be overridden to be 13px but the score style is supposed to be global and need a 32px style.) So I was tempted to use
.score { font-size: 32px !important; color: #777 !important }
because the !important can act as the "second level" which override everything ordinary, and act as a global style.
Is this a good way or better way? One catch is that if sometimes we might have a CSS issue with IE 7 (or IE 6), that we need a separate stylesheet such as ie.css, and in there, there might be also
#summary-panel { font-size: 12px !important }
so in this case, the !important will be overridden because the one having an id will always win over just classes. So is there a better way?
Maybe this?
#summary-panel.score { font-size: 32px; }
I guess I'm not sure how many styles you want to add or if the question is how to do this without adding any new styles, in which case I'd say there is not a better way.
This is where you use span.
For example the markup:
<div id="sometext">
<p>Lorem ipsum <span class="score">test</span> dolor sit amet</p>
</div>
And the CSS:
div#sometext {
font-size: 12px;
color: yellow;
}
span.score {
font-size: 42px;
color: green;
}
this question is about global style.
So solution such as #some-id .score
is NOT a solution
[...]
.score is NOT a solution So is there a better way?
there is no answer, all the comments you got in the first answer are valid and polite, but I would tell you as a user, that you should not use !important unless in an emergency to override external code that is outwith your control, !important is for user styles
CSS is a mindset, a suggestion, your request (with a please ;) to the browsers how you would like your styles displayed - at the minute you seem to be struggling between the mindsets
The logical programmer side wants a "global" style, and I believe most programming languages have "globals" ? CSS is not a programming language it's a markup language.
Anyway, the recent last 3-4 years CSS'ers have been encouraged to "class everything" YUI and Blueprint and other frameworks would have us do so.. but that means you should not use ID's because as you rightly point out they override.. they are the ultimate in the CSS Specificity Wars.. BUT as an efficient CSS coder you need to use ID's - that is best practice isn't it? - so if you do need to mix them then you should group your ID selectors and if necessary group the class selectors as was suggested to you
there really is no answer here (except there no such thing as global styling unless you pass it down via ID's and inheritance, it's a coding preference rather than a right/wrong answer

Make entire CSS sheet !important

Is there a way to make an entire CSS Style sheet take precedence over another? I know you can do the !important but can I do that with one line rather than modify all thousand properties on the sheet?
Thanks!
Make sure the stylesheet you want is called last (or a specific style you want is called last). For example, using this:
span { color: red; }
span { color: blue; }
...will turn all text in <span>'s blue. Take a look here.
Rules with identical specificity that come later will overrule previous ones, so if both style sheets contain the identical selectors, you should be able to do this by just loading the one before the other.
If they contain different selectors, like
#navigation h3 { color: red }
and
.mainpage .navmenu h3 { color: blue }
you are likely to get specificity conflicts. The only blanket solution for that is indeed !important (although that is really, really terrible architecturally. Are you sure you need this? Maybe explain why, it's possible somebody is able to come up with a better solution.)
There is, however, no single-line directive to elevate the "importance" of one style sheet over the other.

Resources