What are the implications of using "!important" in CSS? [duplicate] - html

This question already has answers here:
What does !important mean in CSS?
(5 answers)
Closed 3 years ago.
I've been working on a website for a few months, and a lot of times when I've been trying to edit something, I have to use !important, for example:
div.myDiv {
width: 400px !important;
}
in order to make it display as expected. Is this bad practice? Or is the !important command okay to use? Can this cause anything undesired further down the line?

Yes, I'd say your example of using !important is bad practice, and it's very likely it would cause undesired effects further down the line. That doesn't mean it's never okay to use though.
What's wrong with !important:
Specificity is one of the main forces at work when the browser decides how CSS affects the page. The more specific a selector is, the more importance is added to it. This usually coincides with how often the selected element occurs. For example:
button {
color: black;
}
button.highlight {
color: blue;
font-size: 1.5em;
}
button#buyNow {
color: green;
font-size: 2em;
}
On this page, all buttons are black. Except the buttons with the class "highlight", which are blue. Except that one unique button with the ID "buyNow", which is green. The importance of the entire rule (both the color and font-size in this case) is managed by the specificity of the selector.
!important, however, is added at a property level, not a selector level. If, for instance, we used this rule:
button.highlight {
color: blue !important;
font-size: 1.5em;
}
then the color property would have a higher importance than the font-size. In fact, the color is more important than the color in the button#buyNow selector, as opposed to the font-size (which is still governed by the regular ID vs class specificity).
An element <button class="highlight" id="buyNow"> would have a font-size of 2em, but a color blue.
This means two things:
The selector does not accurately convey the importance of all the rules inside it
The only way to override the color blue is to use another !important declaration, for example in the button#buyNow selector.
This not only makes your stylesheets a lot harder to maintain and debug, it starts a snowball effect. One !important leads to another to override it, to yet another to override that, et cetera. It almost never stays with just one. Even though one !important can be a useful short-term solution, it will come back to bite you in the ass in the long run.
When is it okay to use:
Overriding styles in a user stylesheet.
This is what !important was invented for in the first place: to give the user a means to override website styles. It's used a lot by accessibility tools like screen readers, ad blockers, and more.
Overriding 3rd party code & inline styles.
Generally I'd say this is a case of code smell, but sometimes you just have no option. As a developer, you should aim to have as much control over your code as possible, but there are cases when your hands are tied and you just have to work with whatever is present. Use !important sparingly.
Utility classes
Many libraries and frameworks come with utility classes like .hidden, .error, or .clearfix. They serve a single purpose, and often apply very few, but very important, rules. (display: none for a .hidden class, for example). These should override whatever other styles are currently on the element, and definitely warrant an !important if you ask me.
Conclusion
Using the !important declaration is often considered bad practice because it has side effects that mess with one of CSS's core mechanisms: specificity. In many cases, using it could indicate poor CSS architecture.
There are cases in which it's tolerable or even preferred, but make sure you double check that one of those cases actually applies to your situation before using it.

!important forces the statement to always apply, doing these things:
even if the selector is less specific and lower level, it now beats higher specificity selectors
if there are further occurrences of that statement that would normally override that one, it does not override the important statement any more
Most of the time, !important can be avoided because specificity of selectors handles which one takes effect, which is the idea of cascading styles. However, there are some situations (can't quite remember the exact one) where the specificity isn't that logical and I have to force !important on the statement.
Reasons not to use/avoid !important?
prevents users from using custom stylesheets (which now can't override the rules that are marked as important) which breaks accessibility for some people
makes code more difficult to read because the mind normally takes specificity quite easily, but remembering what is !important makes it harder to read

I think it is important that we touch on this again, here at the end of 2014 when more rules are being added into the working draft, it is so important not to impose restrictions upon your users. I have wrtten this small example to explain a possible scenario in which such a thing takes place. This is taken from a REAL website I have visited on the web, and I see it, sadly, more often than not.
Form Text Editor Fields
You have a website, and your website depends on filling out forms and editing text. To try to minimize eye strain you try to go with a style you think everyone will be okay with, and since your users mainly visit at night, you decide to make your background color to be white, and then make the text color to be black. The form is blank by default, so you type in text (this time) to make sure it works:
...
background-color: black; /* I forgot important here, but it works fine on its own */
color: white !important;
...
A few months later, users complain that white-on-black is too eye straining but the other half love it, what do you do? you add a custom theme that uses !important to override the internal styles so that BOTH parties are happy, which is what it is SUPPOSED to be used for:
...
background-color: white !important;
color: black !important;
...
Now, what happens here? What did you expect. If you properly remember the !important tags in the first set, you would have noticed it didn't work and probably remembered that you needed to delete the !important tags off. BUT you forgot one..
RIGHT, you get white text on white background, and the user can no longer read your webpage at all if they try to use this new style (assuming you kept it).
Of course, You don't realize this because the textbox is empty. And You ASSUME that it will work! (Assumption is a developer's worst enemy, it's right up there with pride and arrogance).
Make and Follow Self Implied Rules
So, the basic rule should be only use !important when designing OVERRIDES to an original complete set of css rules. Remember that it is meant for exceptions and disturbs the natural order and meaning of css in the first place. In MOST cases you will not need to use it at all.
Know How Users Customize Their Colors
With the existence of such tools as extensions and the presence of sites like 'userstyles.org' and it's stylish counterpart, you run the risk of alienating your users by using the !important tag at all! Keep in mind that stylish will not override them.
Never Restrict Your Visitors
If you use !important on a style, make sure you make it possible for the user to turn that style off (and i dont mean via the web browser's internal 'on/off' switch). And for heavens sake don't make it DEFAULT.
Ads
People are less and less using stylish for ad removal, so I don't think protecting ads with !important really is an issue here. It will just annoy someone trying to customize your site.

A little late to this question but it's saying "no matter what other styles are applied, ignore them and use this one". You may find it a little confusing with the ! infront (of the !important) because thats a not operator in javascript but in css it's called a delimiter token that just says to take priority. Heres an example.
Without !important:
.set-color{
color: blue;
}
.set-color{
color: red;
}
outputs RED
!important on bottom attribute (of same)
.set-color{
color: blue;
}
.set-color{
color: red !important;
}
outputs RED (would have been red anyways)
!important on top attribute (of same)
.set-color{
color: blue !important;
}
.set-color{
color: red;
}
outputs BLUE (says ignore red, use blue)

For me, using !important is a bad CSS practice. It disrupts the natural flow in applying the css rules where in properties are applied from top to bottom. With !important, the property will now give priority to the latest important value.
It's just like using the goto keyword in scripts. Though its are perfectly legal, it's still best avoided.

I wouldn't advise you to use it unless it's a necessity, which sometimes might be the case with you, as you're working on an existing project. But try to stay away from it and use as little !important as possible.
The problem is if you use too many of them then one might inadvertently overwrite the other. Your code is also much less legible and anyone who comes after you to maintain this will tear his/her hair apart, as trying to find !important every time you do something in the CSS is a royal pain.
Check this: http://webdesign.about.com/od/css/f/blcssfaqimportn.htm

Well, i think using !important is sometime "must to do job" if you want overdraw wp-plugins default properties.
I used it just today and it was the only way to finish my job.
Maybe is not good way to do something but sometime is the only way to do it.

!important is a factor, That can vain your code for something that is overridden
the ! in it does not mean Logical not, such here it gets disconcerting with that among that code. !important is frequently a colossal mishap in computing.
For Example if you want to make it display: block;
but you've already defined display: none;:
p {
display: none;
display: block !important /*Now overriden*/;
}
<p>Some Paragraph</p>
!important is a best avoided keyword, When to use it, It may be a Influential time, Please click this link to see when to use !important, !important Style Rule - CSS-Tricks
no madder what

The problem with !important is that with CSS you MUST in all cases try to avoid deep selecting (more priority), because in the future you or someone else (often for big projects) will need to override these styles WITHOUT changing the original style and then this one will have limited freedom to do that.
He will need to use !important, too with deeper selector.

Related

How to debug CSS specificity problems?

I've developing an app with Vue, and a third-party template, and dynamic plugins, and all kinds of trickery. I'm have a really hard time with the CSS.
Often I need to style particular element on the page, an <input> for example, and I can't figure out how to write a selector that actually works. The input may have been created dynamically by some Javascript and may have had CSS applied programmatically.
So I go to Firefox Web Developer, click on the element, and see a bunch of CSS classes. I create a rule:
.myCustomClass {
color: red;
}
put myCustomClass in the class="" tag in the <input>, and... nothing.
I'm thinking I need to prefix it like this:
.someOuterClass .someInnerClass .myCustomClass {
color: red;
}
but that rarely works. Sometimes I give up and add !important. Sometimes that works, and sometimes it doesn't.
So my question is, can I examine the classes that I can see in Web Developer and somehow derive a rule that is specific enough that it will always work?
I've read about specificity, but it's not helping.
Specificity is a PITA sometimes, especially when other 3rd party libraries are adding stuff to the mix.
Here are a few things you can try:
Make sure to add your styles to the END of the CSS. Theoretically, you can affect the order Webpack includes CSS (I've never tried it)
Add an ID not a class to a wrapper outside the elements you want to change. Then reference this ID in the CSS chain eg: #myAppID .className .subClassName {} Basically ID's are stronger than classes in CSS specificity. I would try to do this at a page/view level to make life easier.
If elements are already getting classes (as you see them in the inspector) try to reuse those classes with your "override" CSS. If the classes are modularized (Have a random suffix like someClass__34xft5) you shouldn't use those exact classes since they can change if the source is recompiled. In that case, use a "matching" selector [class^=”someClass__”] to match any selector with that prefix.
Not sure how deep you want to go, but here's an article about overriding Amplify-Vue prebuilt styling.
One caveat, if the CSS is being added inline via javascript somewhere, it's going to be very hard to override. You may want to use !important in conjunction with the above.
"...can I examine the classes that I can see in Web Developer and somehow derive a rule that is specific enough that it will always work?"
Probably, but why bother? You're already adding class attributes to elements. Why not add inline style attributes instead? Adding a bunch of classes or ids just to create a specificity chain to touch up styles is pretty messy...inline styles are barely if at all worse and are clearer to understand.
Inline attributes are the most specific CSS instructions you can give.

More important than !important (a higher level !important)?

The title says most of it. Is there a CSS keyword which overrides !important at one higher level or is there some feature like this planned in any newer CSS spec?
Of course, I know that !important is a bit likely to be used by noobs and that in many cases it is not the best way to go as stylesheets may really suck if badly written. However, sometimes it's useful and even needed.
The strongest style in CSS I can think of is an inline style with !important like this:
<span id="bluebeaver" style="color: red !important;">I am a happy blue beaver</span>
Now let's assume that I cannot edit the HTML and must modify the style from an external stylesheet.
It would be really great to have something like:
#bluebeaver {
color: blue !important 2;
}
If they had levels for it like for instance with z-index.
Is there any solution to this or anything planned with newer CSS specifications?
So far I did not find anything.
Can you show a CSS solution to override an !important inline style or is there definitely no possibility?
Simply remove the style attribute from the element using JavaScript:
document.getElementById("bluebeaver").removeAttribute('style');
Then use your external stylesheet to apply whatever CSS you want.
Two reasons why creating higher levels of !important is not a good idea:
It sets a bad precedent.
Adding !important2 would be caving in to poor-coding habits on a global scale. It would be the W3C sending a signal that anything goes.
You've also opened the door to !important3, !important4, etc. Where does it end?
Lowering standards and expectations is not a good way for the industry to make progress.
It may not even solve your problem.
Consider this: The person who set that inline style to color: red !important, obviously wanted that rule to have the highest priority.
If your idea became real, and there were higher levels of !important, let's say going up to !important10, guess what that person would have used? And you'd still have the same problem, but you'd be here asking if there were any plans for !important11.
No, there is no keyword or other way to make a declaration more important than !important. There is no known activity to change this.
In general, it is possible to override a declaration that has !important by using a rule that also has it and that has higher specificity. However, a declaration in a style attribute has, by definition, higher specificity than any other author declaration. The only way to defeat it is in CSS is to use a user style sheet with !important.
There are non-CSS solutions, but they are rather obvious, such as using JavaScript to simply remove or modify the style attribute.
The highest order I know of is targeting elements that have inline styles applied. You can actually select the element's style data attribute in the CSS selector to override its style! Check this out:
.blue[style]{
color:blue !important;
}
<div class="blue" style="color:red;">SO VERY IMPORTANT</div>
Of course you can even get more specific by targeting the style specifically, such as .blue[style="color:red;"].
You can modify the colour of HTML element using javascript.
document.getElementById('bluebeaver').style.color=blue;
Demo : https://jsfiddle.net/041fhz07/
Try Specificity: If two selectors apply to the same element, the one with higher specificity wins.
Try to style your element the more specific you can. Maybe use:
#bluebeaver span {}
Take a look to this link: CSS Specificity: Things You Should Know
if you want to use CSS only you just declare the new style with !important, the last "important" wins. though I'd avoid using it in the first place unless completely necessary.
it should only be used for styles that are essential for your page/app to work, not things that are expected to change.
another solution is to use JS to remove and/or add classes/id to change the style of the element when you don't want to change the CSS itself.
div.prop1.imp1.imp2 {
background-color: red !important;
}
div.prop1 {
background-color: black;
}
div.prop1.imp1 {
background-color: white !important;
}
If you can't do this since not all elements have the .imp1 class on the list in JavaScript, and you are adding say a highlight on something with a button click (.imp2) . You can specify the 'more important' .imp2 class above the others with !important on it.
This makes the property with the additional imp2 class more important than the .prop1.imp1 style because it is loaded first in the css.

Is element-specific CSS selector bad?

Is p.error better or worse than .error?
I have read that element-specific selectors are bad and should be used only if really needed but noone seems to know why. I mean I do understand that .error is better for code reuse, but is there somekinda specific reason why I shouldn't address class with element always?
CSS selectors are read right to left. So p.error has one additional step to .error. This may result in a smaller set or not - depends on your markup.
However, this is a micro micro optimization. There is not going to be a performance hit unless we're talking about a massive amount of selectors.
Here's a great article on CSS selectors that elaborates on how they are evaluated : http://css-tricks.com/efficiently-rendering-css/
.error is more efficient than p.error .
To understand why this is more efficient I recommend you read this article over at css tricks.
no it's not bad, but it may not always be necessary
tools like Google's PageSpeed and YSlow! refer to these type of selectors as being "over qualified" perhaps that's where you're hearing the "it's bad" part from - reading material
take for example p#myid - an ID should always be unique on a page anyway, therefore there is no need at all to qualify it with the p element. an ID already has the highest weight when specificity is being counted so again it's totally redundant to add the extra part to try and add more specificty.
However with class names like your example it can sometimes definitely be desirable to add the qualifier as you may want the class to be re-usable on different type elements but have different properties depending on if it's a div or a p for example, the "qualifier" then makes the selector slightly more specific
.error {background: red; margin: 5px;}
p.error {margin: 2px;}
The code above means you can use the error class on any element and it will have 5px margins however if you set the error class on a p element the second selector is actually doing something, it's over-riding the first's margins but still getting the background color
So they do a job, but too often you see too many people over qualifying all their elements when it is not necessary.. for example if you're only ever applying that .error class to a p element then you wouldn't need the second selector.
The rule of thumb is to make the selector unique as quickly as possible starting from the right side of it.
Having a very specific selector will not amount to bad performance, but if there are a lot of declarations applicable for an element, then the performance will take a hit. The only concern otherwise is that it increases the no. of bytes to be downloaded for loading the stylesheet. Trust me, Every extra character in HTML passed is evil and will amount to lower page load speed.
During CSS cascading is applied by modern-day browsers, the following is the process that occurs for each CSS property for each web page element:
Gather all the declarations for the property from all the sources. This includes default browser styles and custom user style, as well as author style sheets. If there is more than one, proceed to 2.
Sort the declarations by importance and origin in the following order (from lowest to highest priority):
user agent style sheets (default browser styles)
normal declarations in a user style sheet (a user’s custom style sheet)
normal declarations in an author style sheet (web page style sheets; external, embedded, and inline styles)
!important declarations in an author style sheet
!important declarations in a user style sheet
The one with the highest priority wins. If more than one have the same priority then proceed to 3.
Sort by selector specificity. The one with the most specific selector wins. If no clear winner, proceed to 4.
The one that comes last in the source wins!
If the cascade does not set a CSS property on an element, then the browser will fall back to using an inherited property from the element’s parent (this only happens for some properties), otherwise the property is set to the CSS default value.
According to the above process, if you use a lot of more specific selectors, there would be a choice made after atleast 3 levels deep. Hence, the more the no. of declarations which might be applicable to an element, the lower the performance would be.
So, You must as specific as it makes sense to be.
The reason is specificity. For example...
+1 each access by class
+1 each access by tag
+10 each access by ID
etc.
So, if you have a class and a tag access, that style has a specificity of 2 (1+1).
Later, if you're trying to style all .error elements, but you have a conflicting style in the p.error elements, the higher specificity will win. This may cause some headaches down the line. That is why you may not want to always use tag+class.
(That being said, specificity solves many more problems than it creates, and is generally regarded as Pretty Awesome.)
As a general rule of thumb, the less selectors a browser has to evaluate the better.
p.error isn't necessarily "worse" than .error, if .error is used for multiple tags. e.g. div.error (see a foot note at the bottom).
But if it's only used on a paragraph anyway, then having p.error is just making the browser work harder i.e.
First it will have to find all elements with the class attribute error and then filter these by only having tags that are p.
Here is some interesting reading on Optimize browser rendering on Google's Page Speed site.
Foot Note
However if you need to use a class on multiple tags, it's probably best only to put in the css styles which apply to those tags instead of trying to separate it. e.g.
.error
{
color:red;
}
h1
{
font-size:2em;
}
p
{
font-size:0.8em;
}
<h1 class="error">Bad Heading!</h1>
<p class="error">bad!</p>
So that kind of defeats the need to prefix classes with tags anyway.
I hope this helps!

When to use the !important property in CSS [duplicate]

This question already has answers here:
What are the implications of using "!important" in CSS? [duplicate]
(9 answers)
What does !important mean in CSS?
(5 answers)
Closed 4 years ago.
Consider:
#div p {
color: red !important;
}
...
#div p {
color: blue;
}
I understand how !important works. In this case the div will render red because now it has priority (!important). But I can't still figure out an appropriate situation to use it in. Is there an example where !important saves the day?
This is the real life scenario
Imagine this scenario
You have a global CSS file that sets visual aspects of your site globally.
You (or others) use inline styles on elements themselves which is usually very bad practice.
In this case you could set certain styles in your global CSS file as important, thus overriding inline styles set directly on elements.
Actual real world example?
This kind of scenario usually happens when you don't have total control over your HTML. Think of solutions in SharePoint for instance. You'd like your part to be globally defined (styled), but some inline styles you can't control are present. !important makes such situations easier to deal with.
Other real life scenarios would also include some badly written jQuery plugins that also use inline styles...
I suppose you got the idea by now and can come up with some others as well.
When do you decide to use !important?
I suggest you don't use !important unless you can't do it any other way. Whenever it's possible to avoid it, avoid it. Using lots of !important styles will make maintenance a bit harder, because you break the natural cascading in your stylesheets.
Overwriting the Style Attribute
Say in the example that you are unable to change the HTML source code but only provide a stylesheet. Some thoughtless person has slapped on a style directly on the element (boo!)
div { background-color: green !important }
<div style="background-color:red">
<p>Take that!</p>
</div>
Here, !important can override inline CSS.
This is a real, real life scenario, because it actually happened yesterday:
Z-index in jQuery dialog. Autosuggest list not displayed properly
Alternatives to not using !important in my answer included:
Hunting down in JavaScript/CSS where a certain elusive property was being applied.
Adding the property with JavaScript, which is little better than using !important.
So, a benefit of !important is that it sometimes saves time. If you use it very sparingly like this, it can be a useful tool.
If you're using it just because you don't understand how specificity works, you're doing it wrong.
Another use for !important is when you're writing some kind of external widget type thing, and you want to be sure that your styles will be the ones applied, see:
Appended control's CSS
You generally use !important when you've run out of other ways to increase the specificity of a CSS selector.
So once another CSS rule has already dabbled with Ids, inheritance paths and class names, when you need to override that rule then you need to use 'important'.
!important is somewhat like eval. It isn't a good solution to any problem, and there are very few problems that can't be solved without it.
I have to use !important when I need to overwrite the style of an HTML generated by some JavaScript "plugin" (like advertising, banners, and stuff) that uses the "style" attribute.
So I guess that you can use it when you don't control the CSS.
Strictly speaking you shouldn't need to use !important if you've structured your CSS well and don't have too many degrees of specificity.
The most appropriate time to use !important is when you have one exceptional style that you want to style outside of your site's normal cascade.
Using !important is generally not a good idea in the code itself, but it can be useful in various overrides.
I use Firefox and a dotjs plugin which essentially can run your own custom JS or CSS code on specified websites automatically.
Here's the code for it I use on Twitter that makes the tweet input field always stay on my screen no matter how far I scroll, and for the hyperlinks to always remain the same color.
a, a * {
color: rgb(34, 136, 85) !important;
}
.count-inner {
color: white !important;
}
.timeline-tweet-box {
z-index: 99 !important;
position: fixed !important;
left: 5% !important;
}
Since, thankfully, Twitter developers don't use !important properties much, I can use it to guarantee that the specified styles will be definitely overridden, because without !important they were not overridden sometimes. It really came in handy for me there.
The use of !important is very import in email creation when inline CSS is the correct answer. It is used in conjunction with #media to change the layout when viewing on different platforms. For instance the way the page looks on desktop as compare to smart phones (ie. change the link placement and size. have the whole page fit within a 480px width as apposed to 640px width.
This is a real-world example.
While working with GWT-Bootstrap V2, it will inject some CSS file, which will override my CSS styles. In order to make my properties to be not overridden, I used !important.
I'm using !important to change the style of an element on a SharePoint web part. The JavaScript code that builds the elements on the web part is buried many levels deep in the SharePoint inner-workings.
Attempting to find where the style is applied, and then attempting to modify it seems like a lot of wasted effort to me. Using the !important tag in a custom CSS file is much, much easier.
I am planning to use !important for a third-party widget meant to be embedded in a large number of websites out of my control.
I reached the conclusion !important is the only solution to protect the widget's stylesheet from the host stylesheet (apart from iframe and inline styles, which are equally bad). For instance, WordPress uses:
#left-area ul {
list-style-type: disc;
padding: 0 0 23px 16px;
line-height: 26px;
}
This rule threathens to override any UL in my widget because id's have strong specificity. In that case, systematic use of !important seems to be one of the few solutions.
You use !important to override a css property.
For example, you have a control in ASP.NET and it renders a control with a background blue (in the HTML). You want to change it, and you don't have the source control so you attach a new CSS file and write the same selector and change the color and after it add !important.
Best practices is when you are branding / redesigning SharePoint sites, you use it a lot to override the default styles.

Are fully qualified CSS styles efficient?

In creating CSS styles one approach seems to be a fully qualified style such as
#pnlImage div.ipd-imageInfo div.ipd-tags span.ipd-tag
compared to a shorter definition such as
div.ipd-tags span.ipd-tag
which would uniquely identify the style as well. However, if the site is expanded or changed the 2nd style runs the risk of not uniquely identifying the element.
Is there a performance hit from fully qualifying a style, i.e., it is longer? Are there some guidelines/best practice references for style naming?
Thanks
Google (not a search, actually them) seems to think that it does cause a performance hit.
Also, the Mozilla foundation has an article "Writing Efficient CSS for use in the Mozilla UI" that outlines the possible performance pitfalls of CSS selectors in their browser(s), and how to optimize your style rules for their rendering engine. Their article has tons of examples of what's good and what's bad. Please keep in mind this is only relevant to their browsers, though.
There are also some benchmarks publicly available, about CSS selectors affect on rendering speeds:
http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/
http://blog.archive.jpsykes.com/153/more-css-performance-testing-pt-3/
I, however, think this is, for the most part, horse manure. You can effect FAR greater change on your page's loading/rendering speed by using some other simple optimizations. I believe that your sanity, and a well-organized code base should come first. If this were as big of a deal as some make it out to be, we'd all be back using HTML < 4 attributes (bgcolor=, border=, etc) to style our web pages.
Looking up an #id is fast.
Looking up a tag is a bit slower.
Looking up a .class is the slowest.
Starting your selectors with a faster lookup will reduce the number of lookups required for then next part. That is, if I wrote p.myClass, then the browser can very quickly find all the p tags and then it only has to loop through those to check for the class name.
That said, it would rate the maintainability of your CSS file higher than its rendering speed. Blah blah blah premature optimisation blah blah.
You might be interested in David Baron (Mozilla)'s Google Tech talk.
I have a site where another designer used heavily qualified styles and maintenance is a nightmare. (the qualified styles are only one part of that)
Basically, you can't touch or simplify the html structure without it breaking half the styles, and the styles often don't cascade properly to new content additions. If you add new css you in turn have to qualify your new rules heavily or half of them end up overridden by some existing rule because it contains so much specificity.
So from a maintenance standpoint it's not efficient. Also not efficient from a typing standpoint either.
I don't see how a theoretical answer is possible: the answer is implementation-dependent; so I suggest you profile it to be sure.
Is there a performance hit from fully qualifying a style, i.e., it is longer?
Yes, on every dynamic change of the DOM-tree, the CSS-expression has to be rematched against at least some nodes. I doubt this will lead to any noticeable delay, though.
Your stated objective (making the selectors robust against changes to the page structure) is not quite solid: hardcoding intricate details about the site structure into the CSS will just mean that you'll have more statements to maintain and update when the page structure changes.
If it's under your control, stick with simple classes (even if you have more of them) and as few levels as possible (doing some relative sizing of fonts is the only use case where I have used several levels, and even this was somewhat superfluous). It just wastes too cognitive capacity to keep track of the page structure in your head.
Although your question is about the performance, (and I would suggest, measure it..) I would really like to add that you should always try to use the shortest definition possible to identity the correct elements.
The reason is not the file size, but the ability to extend your site without altering the main css.
For example you've got this part in your html site:
<div id="Header">
<h1>Css example</h1>
<h2>Welcome to the css example site</h2>
<p>An example page by davy</p>
</div>
and this is the css:
#Header
{
background-color: #ffeedd;
padding: 1em;
}
#Heading h1
{
font-size: 3em;
color: #333;
}
#Heading h2
{
font-size: 1.5em;
color: #666;
}
#Heading p
{
margin: 0 0.5em 1.5em 1em;
font-size: 1.1em;
color: #999;
}
And later on you'd get to a page where you'd like your header to have a different background.
Had you chosen to use div#Header in you main css file, you'd either have to change the html (which depending on your system might mean creating a different template/masterpage) to add an extra class, or create a more qualified css selector such as body div#Header.
Using the shortest selector you could still use div#Header { background : ... } to change your header. You can either create an extra css file and load that into your header on that page (if allowed) or add a style definition directly to your <head> section. The nice thing about this is your css file does not grow with selectors for each different page, and you can keep clear of classitis.
You could also use it to switch the sizing method of your page (static/fluid) so that one template/masterpage uses the default css, and the other derives from that template/masterpage and just links a css called FluidWitdth90.css to change the template to 90% width fluid layout.