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!
Related
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.
So, I was looking at a tut on youtube the other day, and this guy kept defining css rules with classes really weirdly, and I wondered if one of u guys could explain the necessity of it: here is the code:
ul.class li{
color:#fff
}
Why can't he just do:
.class{
color:#fff
}
Thank you for reading my question, I hope you understand what I am asking for.
Video: https://youtu.be/2wCpkOk2uCg
P.S - Sorry for the giganticly large title 😏
When you put the element before the class, CSS only applies the styles to the members of that class that are of that specific element.
For example, if you had .class applied to 3 headers and 3 paragraphs, writing p.class would only affect the paragraphs.
With ul.class you're saying "Apply this styles to all the ul's with this class. If you only use .class you're saying "Apply this styles to ANYTHING that has this class". It's very different. :)
I can think of at least two reasons to include the element name as well as the class:
Specificity, i.e., which CSS rule takes effect on a target element when multiple rules apply to to it. There is a specificity algorithm that determines which rule is applied when multiple rules are in competition. This awesome Specificity Calculator is a great tool to help you understand the algorithm. So, in short, including the element name and the class gives it additional weight.
Documentation in your CSS. I tend to include the element as well as the class, e.g. h1.customer-name, to self-document what type of element the rule is being applied to. When I see .customer-name without the element name, I am not totally confident in what type of HTML element it is. Doing this means I don't have to keep the HTML structure in my head or consult the HTML repeatedly while I work on CSS. But this is pretty dependent on one's approach to CSS as well as the tools used, so I'm not sure I would consider it a good idea across the board.
And one more, but not least important thing. If you adding the tag name before the class name (such as span.class{}), so you got more specific rule and it's have bigger priority (no matter in which order that rules writter in css file). For example, if you write two rules:
.class { color: red }
and
span.class { color: blue }
you will get a blue text as a result.
I have some html markup & css styling that will be embedded on several thousands of different websites. I want this section to only use my own stylesheet, while ignoring the original site's css.
Apart from using unique prefixes for all classes and id's, is there a way to not apply site wide css rules on a certain area, and only use my own styling?
FYI !important declarations in user CSS will always win against CSS Author and User Agent ones (resource: the cascade on Sitepoint), but that's not what you're competing with.
There's no way to only apply your CSS while completely ignoring the rest of the page, afaik (the C in CSS is there for a reason ;) ). But nevertheless, here's a bunch of things that should help:
!important is very powerful. Only other declarations with this modifier have a chance to still be applied
same for inline styles (not sure if it's as needed as it is for those dreaded HTML emails though)
id have a strong specificity. A selector with 412 classes and no id has less specificity than one with 1 id and no class (that's why it's a bad practice according to OOCSS and css linters based on it. Ymmv)
a nice trick allowing to artificially add to CSS specificity is .c.c { prop:val}: twice the specificity of .c {} and exactly the same scope. Imagine this with id ;) (you can also have an id on each and every ancestor of an element but you can't have 2 id on the same element)
initial and unset'd have been nice if it was supported by IE... Would be even better: all property but it's IE11+ and not in Safari
So you'll have to read carefully MDN for each property you want to reset and apply its default value. Or read this amazing answer here on SO on a related question: https://stackoverflow.com/a/18464285/137626
Don't forget about declarations inside Media Queries that could apply on client websites: you (or you clients) won't see them until they resize their browser.
I care a lot about not having not too much specificity in general rules and then specific ones in default resolution, but in that last MQ (320 or 1600+) of a given project, I don't really care anymore if it' more convenient for me (i.e. faster) as I know for sure that I won't need to override it later. Ever.
EDIT: don't forget to take into account pseudos :before and :after. Normalize.css is now declaring *, *:before, *:after { (-prefix-)box-sizing: border-box } and that may be surprising if you also use them. Better not use them imho as they can't be styled in style attribute (same problem with MQ).
To annihilate any style these pseudos could have, this code:
high-specificity-selector *:before,
high-specificity-selector *:after {
content: none !important
}
should be enough: no content, no pseudo.
/EDIT
If you're pretty serious about your project (thousands of websites, wow), you could also automatically test for the CSS applying on client's website in the wild, with tests verifying:
the CSS values of a bunch of properties on a bunch of elements of your widget. Resource: http://csste.st/tools/
the rendering of your widget compared to an initial screenshot with teh mighty PhantomCSS (based on CasperJS, itself based on PhantomJS. Casper tests in WebKit but there are clones testing in Gecko/SlimerJS or with IE/TrifleJS)
I'm wondering if there is any difference between div.class and .class as CSS selectors if there is only one tag (the DIV) with that attribute. Same thing for IDs: div#ID and #ID.
Any idea what, if anything, is the difference? For me, I use the class or ID in these situations; but only because it's quicker to type.
They are more specific, so long ones will override the shorter version if they conflict. div.foo will have a specificity of 11 while .foo has a specificity of 10.
Since they are more specific, you know exactly which nodename the class applies to instead of being a universal rule for all node names, this can help if you have a huge application with tons of elements that all have the same class names, it can lessen the time for you to find the element in the source/text editor.
There is only a VERY SLIGHT difference in specificity.
p#id is (0,1,0,1)
and
#id is (0,1,0,0)
in otherwords, the tag itself doesn't hold very much specificity at all compared to an ID, and relying on that kind of tiny specifity to overrule things is almost never needed in my experience.
More importantly, NOT tag-qualifiying selectors is more efficient for the browser to render.
Sticking to just a class or id, as you do, means that your CSS will still apply if the HTML tag is changed to a different tag.
Most of the time, this is probably exactly what you want — classes are there to allow you to add a custom layer of meaning on top of HTML.
In general, your selectors should be the minimum required to express your meaning.
Usually those longer selectors come in handy once the majority of the CSS has already been done. Sometimes you want to tweak a little thing here and there - say - differenciate between p.error and div.error for example. So instead of adding another class - and thus having to touch the HTML - you can simply add an element name to your selector instead, for more fine grained control.
No, there is no difference if you only have DIV tags of the specific class or ID.
Given this:
<a class="details" href="#">more…</a>
...
<input type="submit" value="Gogogo">
Say that both should have very similar appearance, because that's what the designer wants. Do you do this:
<a class="fancybutton" ...
<input class="fancybutton" ...
.fancybutton { /* ... */ }
or this?
a.details, .someform input[type="submit"] { /* ... */ }
I'm struggling with this issue and I'm not sure where to go. It seems to be a choice between having a really clear stylesheet vs. nice markup that isn't littered with classes.
When do you choose one over the other?
The main reason to choose classes over more fancy CSS selectors is compatibility. Several versions of at least one major browser still in use don't support more advanced selectors properly and thus it's actually less painful to just use classes, since they "just work".
IE6 doesn't support input[type=submit], so if I'm developing for it, I'll definitely go for the class.
I'd generally use class because that has wider support than attribute selectors amoung browsers. Until the vast majority of the population have a browser that supports the CSS attribute selectors I would continue to uses classes in such a case.
I'd say, within complaint browsers, that the answer is specificity. Look to the breadth of the application of the style and define it with sufficient specificity to be unambiguous within the scope of your web-app.
Also, don't be afraid to use more than 1 style class on an element to develop a layered presentation approach, i.e. class="blackborder smalltext centred".
Like other users have said, using classes is good because it really simplifies the question of browser compatibility (problems arise when you try to use fancy CSS 2 selectors).
Another great reason to use simple class-based (or id-based, if possible) selectors over complex CSS 2 selectors is speed.
From google's "Optimize browser rendering", descriptions of why you should try to use simple selectors (class-only/id-only selectors are very simple):
Descendant selectors are inefficient because, for each element that matches the key, the browser must also traverse up the DOM tree, evaluating every ancestor element until it finds a match or reaches the root element. The less specific the key, the greater the number of nodes that need to be evaluated.
Child and adjacent selectors are inefficient because, for each matching element, the browser has to evaluate another node. It becomes doubly expensive for each child selector in the rule. Again, the less specific the key, the greater the number of nodes that need to be evaluated. However, while inefficient, they are still preferable to descendant selectors in terms of performance.
And a specific note about class-selectors over descendant selectors from the same article:
Use class selectors instead of descendant selectors.
For example, if you need two different styles for an ordered list item and an ordered list item, instead of using two rules:
ul li {color: blue;}
ol li {color: red;}
You could encode the styles into two class names and use those in your rules; e.g:
.unordered-list-item {color: blue;}
.ordered-list-item {color: red;}
If you must use descendant selectors, prefer child selectors, which at least only require evaluation of one additional node, not all the intermediate nodes up to an ancestor.