css selector specificity conflicts due to multiple stylesheets - css

Ok, I've been reading through stackoverflow css selectors. on the thread here what is the differences in this syntax? What does the ^= mean? What is it selecting? all?
[class^='Rating']
and
div.Rating0_5
Also, there's a statement here that reads:
Note: Repeated occurrances of the same simple selector are allowed and do increase specificity.
What does that mean?
I'm asking because I'm having to clean up alot of CSS code on a website. There are over a dozen stylesheets each containing 200+ lines of code, and there are styles that are overriding each other among the stylesheets, maybe even within them if repeated occurences increase specificity. It's painstaking to go line by line through the stylesheets to find out what particular class, div, etc is over-riding another and some of the specificity is seven selectors deep! It's almost impossible for me and very stressful.
Is there a tool to use that will target styles overwriting other styles? Is it easy to use and what does it do exactly? If not, how can I write my CSS with enough specificity without having extremely long selectors to hopefully ensure uniqueness so that they will not be overwritten by another stylesheet of rules?
Thanks, I hope this makes some sense and someone has had this experience.

^= is "starts with" for CSS selector. In your case it will apply to classes with names starting with "rating".
With traditional CSS you do have to make really long selectors to be specific and I think the statement meant you can have duplicate selector and the styling will be combined.
In terms of cleaning up the CSS I don't have a good suggestion for an automated tool but you can take a look at http://sass-lang.com/ (SCSS) for a better syntax layer on top of CSS that does variable and inheritance of selectors. Does clean up CSS a lot.

Related

SASS nesting(for readability), is it a bad practice?

A more experienced co-worker told me to nest all my SCSS, so it would reflect its look in HTML, claiming it would do wonders for readability.
I am really concerned that this is unnecessary and could potentially slow down the application(angular) dramatically.
in the reformatted document, the selectors are going 5 levels in, while in the original it never passed the 3.
What is ts the best practice to use nesting is SASS? should it be used only when it would its necessary for specificity purposes? or it can be a better way for formatting my document?
I would try not to directly nest them in a way that's identical to the nesting of the HTML as you're quite right, you would have an unnecessary amount of selectors in your CSS.
There is a great book on https://smacss.com/ that teaches you to split your code into modules instead. I would recommend sectioning your HTML to blocks/modules and nesting relevant selectors rather than all selectors.
Rule of thumb: the more selectors you include, the stronger priority it holds when styling.
Note: I would recommend looking into stylus as I think this improves readability over SCSS.

CSS selectors, tagname + class vs class

Lets imagine very simple case:
div.className{}
vs
.className{}
Which option is faster and why ?
.className{} is faster in downloading, because of smaller size of the css file.
It is also faster when rendering page, because it is not necessary to look for div elements.
A guideline from google:
Avoid qualifying ID and class names with type selectors. Unless
necessary (for example with helper classes), do not use element names
in conjunction with IDs or classes.
Avoiding unnecessary ancestor selectors is useful for performance reasons .
One very important difference between div.classname and simply .classname is in something called selector specificity. It is a set of rules which defines which selector gets more weight once the browser starts going through all the selectors that potentially have influence on a particular element.
ne of the most basic rules of CSS is that selectors can be redefined in a way that whatever definition comes last and has influence on a particular element its the one that is going to be used (the sole exception being when using !important which always takes precedence).
Now in the above example redefining the .class selector should actually hide the text but instead its still visible. How is that possible if we said that latter rules always take precedence? Its because the div.classname rule has a higher specificity that .box since it actually gets points for containing both an element (div) and a class selector (.class) in its selector declaration (div.class).
Of course the div.class rule will be applied only on a div element but since class selectors are often reusable pieces of code there is plenty of situations when they are used on divs.
Although the rules in the official W3 specification are not that hard to understand they are sometimes pretty hard to remember. That's why I would like to recommend an excellent article on CSS selector specificity which can be found here.
In my opinion selector specificity is by far the most important thing to master when it comes to tracing inheritance problems with CSS stylesheets.
For Example
Find some more info
Follow Up

Is having a long CSS selector bad?

Is a selector like
.a, .b, .c, .d, .e, .f, .g, .h, ......... , .zzzzz {font-size:16px}
bad for performance? If yes how and if no why?
I Googled and read a lot of posts including the ones by Mozilla and couldn't find any mention of having a large number of class names as a selector being bad.
No, there is no performance problem here.
What is bad is a long selector involving many checks but your selector is in fact a sequence of selectors, equivalent to
.a {font-size:16px}
.b {font-size:16px}
...
Selectors with just a class are among the most efficient ones.
There's no real problem, even if you probably should have less classes in order to manage your code more easily.
This is the valid syntax for assigning a common properties to multiple classes at a time. there is no down side effect.
Saving a single bite is good. Yup as #dystroy said it's doesn't impact that much on your page performance but it's not a good coding particle & also it's hard to manage your code.
Write like this:
body{font-size:16px}
You didn't choose a large selector, you just assigned many selectors to your stylesheet. A large selector would be for example:
header nav ul li a
As the browser uses selectors from right to left the key-selector (the last selector in line, in this example the anchor-element a) is too general. When beginning to render the style the browser begins to grab for all elements according to the key-selector, what would probably mean, that it got much more elements, as effectively needed. In this example it would be much better, if navigation items get unique classes, so the stylesheet must only be applied to following selector:
.primary-link
So, it's import the right key-selector for your styles, to reduce the rendering time to a minimum.
If you want to read something interesting about CSS selectors and performance I can recommend that page: http://learn.shayhowe.com/advanced-html-css/performance-organization

CSS Specificity Filter

This is a long shot, but is there a tool available that optimizes CSS selectors by removing unneeded specificity?
I find that when I write CSS, I deliberately make my selectors more specific than necessary to avoid conflicts and for quasi-documentation.
It would be great if there were a tool that could analyze a given group of rules, determine their "uniqueness" in terms of overlap with other rules, and then strip away any unnecessary specificity.
I can't even begin to imagine how a tool developer would approach all of the scenarios this would require, but I've been blown away by others' ingenuities in this area before and figured it was worth asking.
Update:
I've added a bounty to this question, and the more I think about it, the more I realize how valuable a CSS Specificity Filter would be.
For example, when working with Nested Rules/Selectors in Sass and LESS, excessive nesting is a common and well-known antipattern that can easily lead to overly specific selectors.
There's a good illustration of this in the excellent TutsPlus course Maintainable CSS with Sass and Compass:
body {
div.container {
p {
a {
color: purple;
}
}
}
}
Sass will follow these nesting instructions and produce the following CSS output, raising no objection to any unneeded specificity:
body div.container p a {
color: purple;
}
If a Specificity Filter did/does exist, however, it would create potential benefits for CSS developers:
You could organize your stylesheets as a 1:1 mapping of the DOM, similar to what you see when you examine style rules in Firebug and Chrome Dev Tools. A smart editor/IDE could auto-populate styles for DOM elements with shared styles/classes. That redundancy would then, of course, be filtered out by the Specificity Filter/Optimizer.
Stylesheets could have their structure pre-populated by a tool that scans the DOM and translates it to CSS selectors/rules. This means a developer would only need to update the HTML; the CSS "tree" would be kept in sync to reflect the current state of the DOM. A smart editor would let you jump to the CSS definition for an element/class for styling -- or even make its style rules visible in a separate panel.
In a way, this almost seems like a step backward - like a feature you'd find in Dreamweaver or WebAssist to help newbs learn CSS. But the basic idea of a CSS selector optimization tool seems like a no brainer, and the type of workflow automation I've described would be the logical next step -- and the catalyst would be the Specificity Filter.
I looked into some of the better-known CSS editors and web IDEs, but haven't found anything offering this type of functionality beyond targeting a single element and generating a selector for it.
Update 2: CSS Selector Performance
In response to Spliff's comment, here are two great articles on CSS selector performance:
Performance Impact of CSS Selectors by Steve Souders
Efficiently Rendering CSS by Chris Coyier
Both agree that micro-optimizing CSS isn't worth the effort, but that over-qualified descendant selectors are "an efficiency disaster." I haven't benchmarked yet myself, but suspect that the kind of "DOM Mapping" approach I'm suggesting would cause a performance hit without an optimization step, either manual or automated.
Related Questions, Links, and Tools:
Points in CSS Specificity
Tool to See CSS Specificity
Tool for Cleaning Up CSS
Order by CSS Specificity
Top 5 Mistakes of Massive CSS
Google: Efficient CSS Selectors
Procssor
Clean CSS
CSS Tidy
You could attempt to take a different approach, try to write your selectors as small (low specificity) as possible. and only make them more specific when needed.
With that way of working you don't need a tool.
Just going to throw this out there-- it doesn't 'answer' your question,but it's a tool I like to spread the word about for people who do a lot of css programming: Firebug.
If you're not familiar with it, it's a tool for web browsers. You pull up your page once it's installed, right click and select 'Inspect Element.' It will show you all css affecting different elements on your page, and is useful for creating clean, precise css code. Also it makes it easier to see instant updates on what your page would look like with slight modifications. It will inform you of useless css code that's being overridden by other css code.
ALSO! Firebug now is available for almost all browsers. Not just Firefox. Personally, I'm partial to using it in Chrome.
We really can't do without specificity because it is the only thing that saves you when you have two or more rules colliding. Specificity brings sanity to the whole jumbled CSS rule, so it is more of a blessing than curse. Some of the stuff you talked about, like the CSS selector, can be done using Firefox/Firebug. I'm more disturbed by browser compatibility.
Actually there's a way you can do this using HTML5 and CSS3. The standard technique is to specify elements using the HTML 5 attribute "data-" and then do CSS selection for this attribute. This isn't the purpose of the attributes, but you can customly specify some elements that you can use to even switch the theme of a site.
So, for example, you can end up creating your specificity filters manually in CSS, by specifying
<b data-specificity=2>test</b>
where data-specificity only matches to parents above.
UPDATE:
Alright, so for example, let's say you have a paragraph class, but you want to specify which parent, or how many parents the paragraph can inherit properties from. You would use rules for each potential parent that can be inherited from:
p[data-specificity="1"]{
color:red;
font-family:verdana;
text-decoration:underline;
}
p[data-specificity="2"]{
color:black;
font-family:arial;
}
div.container > *[data-specificity="2"] {
font-family:impact;
color:blue;
text-decoration:underline;
}
So these rules mean that any p tag which is a direct child of the div container and has specificity 2, is allowed to inherit properties from the div container. The blue color of the div gets inherited by the p with data-specificity 2.
Here's a JSFiddle where you can see this!
The idea is that like this, using HTML5, you can control exactly which elements are allowed to inherit which properties. It's a lot of extra code to write (for both child and parent elements) but you can use this to get rid of some unnecessary specificity
I've never actually seen anyone use this method in practice, I pretty much just cooked it up for you, but I think it could be very useful, what do you think ?

Is there an advantage to using very specific selectors in CSS?

I understand that in jQuery, it's advantageous to be more specific when using selectors so that jQuery doesn't have to traverse the entire DOM to find what you're looking for. For example, $('span.description') is better than just $('.description') if I know that the description class is only ever applied to <span> elements.
Is this the case with CSS, too? Is there any specific advantage for me to use span.description { } instead of .description { }? I'm thinking in terms of speed, optimization, etc. Am I saving the browser any work by telling it exactly where to look?
This is true in CSS -
A good rule is to descend from the nearest ID.
IDs are indexed so locating them is extremely fast. There is no reason to use more than one in your selector.
Google Code- Optimize browser rendering
This answered a lot of questions I had on the subject including this one-
I hope you find it useful.
Read up on css specificity - which is the most important reason to be more or less specific with your css.
http://www.w3.org/TR/CSS2/cascade.html#specificity
As browser performance is pretty much a non-issue (except for in jquery, as you've mentioned), my guideline is to be specific when you are controlling precedence, or when you want to make something a bit more readable in your css. Over specifying can make it tricky to re-use css selectors and make things overly complicated.
Edit
This looks like a bit of a duplicate:
CSS Performance Question
it always depends on your amount of html code and the structure. It is definitely a good idea to use especially ids and appropriate selectors. (ie #nav li instead of li.nav). Since browser first load the html and then apply the css you are helping a lot.
This said, when it comes to pure css (no jquery) the difference in speed is nowadays not easy to distinguish, because the rendering engines are highly optimized - especially when it comes to applying css. So normally it shouldn't matter.
As far as I know, how specific your selectors are make very little difference on the performance.
The two areas where more specific selectors are most useful, is to reduce the risk that it's not applied where you don't want it, and to make one selector take precedence over another.
A more specific rule has precedence over a less specific rule, so:
span.myclass {}
has precedence over:
.myclass {}
(no matter what the order is in which the rules were declared)

Resources