What other justifications are there for using id's sparingly? - html

While I don't need convincing that id selectors should be used sparingly and that class selectors should be used primarily for applying CSS , I'm having trouble explaining it to members of my group project. When we met as a group to go over everyone's HTML and CSS files, I noticed they used id selectors for almost everything(including elements that weren't unique). While I explained that id selectors should be used to style very unique elements only in CSS and class selectors should be used for applying CSS to everything else due to their re-usability, now I'm trying to remember other reasons. So my question is what other reasons are there for using class selectors over id selectors for non-unique elements?

As you mentioned, the uniqueness of ids is reason enough to not use them as selectors, but there are more:
An element can have several classes, but only one id. You might want to same element to be both a .news-article and .breaking-news. If you use JavaScript you can have one class for styling (.unstyled-list) and another for your script (.side-menu). That way you can change your list to .roman-numerals without breaking your script.
What makes ids even worse for applying styles is the combination of their uniqueness and their higher specificity. If you use ids for styling you will surely get stuck in a specificity race (especially if you need to maintain the CSS over time, which is probably the case).

Related

Why are most elements assigned to a class instead of an ID? [duplicate]

This question already has answers here:
What's the difference between an id and a class?
(17 answers)
Closed 8 years ago.
Lately I'm working with a lot of Wordpress themes. When I have to edit a particular element, I usually use Firebug to see the element's name so I can change the CSS. I think I understand the difference between IDs and Classes, Classes are used for a group of elements that you want to share the same styling, and ID is usually used for a single element.
Here's the thing, I'm seeing so many elements in these Wordpress themes that are only used once, but they are assigned to a class. A good example is the website logo. Isn't the logo only used once? Shouldn't it be assigned to an ID? Why is it always assigned to a class?
Needs change often. An element/style that today you think will only be used once may be used multiple times in the future. Maybe you will have your logo more than one time on your site (for example, on your about us page). Perhaps you may eventually incorporate a second search bar. There are very few cases where you know with 100% certainty that the style will only be needed once.
Here's a good read on the subject: http://oli.jp/2011/ids/
http://ryanfait.com/articles/the-difference-between-ids-and-classes/
Ryan says
"I take a different stance than most web designers when it comes to
using ID's and classes. The vast majority of CSS coders use ID's for
any elements that are simply used once on a page. However, I only use
classes to style my websites, but, when I want to use an element in
JavaScript, I use an identifier. From a presentational standpoint,
styling elements with classes looks exactly the same as styling them
with ID's, but the flexibility of classes offers a certain appeal even
if I don't plan on using a class more than once on a page. Also, when
I see an ID in my XHTML, it reminds me that there is some JavaScript
that refers to that element. It's up to you, but so long as you
implement classes and ID's properly, it is more or less a matter of
personal choice when to utilize one or the other."
id is a unique one, but when class its not, you can you one for many selectors
ID's are unique
Each element can have only one ID
Each page can have only one element with that ID
Classes are NOT unique
You can use the same class on multiple elements.
You can use multiple classes on the same element.
Any styling information that needs to be applied to multiple objects
on a page should be done with a class. Take for example a page with multiple "widgets":
There are some reasons why people prefer using classes instead of id's in CSS. (note that for javascript ID's are still commonly used).
The class element is re-usable on that page. This means that you won't have as much duplicated code with Classes as you would have with ID's.
Usually, IDs refer to something very specific, and abstracting would be tough
Any performance gains picked up by using id, is negated by adding any other selector to the left fo that id. Which mainly means that in most uses of id's you won't really have performance gains. (you could even have less performance than if you would just use a class)
Lecture about this:
http://screwlewse.com/2010/07/dont-use-id-selectors-in-css/
http://www.impressivewebs.com/css-specificity-irrelevant/
http://www.baldurbjarnason.com/notes/ids-in-css/
If you're new to web development, just use the simple rule:
If you're trying to apply style to a HTML element, use a class.
If you're trying to interact with a HTML element with javascript, use an ID.
You see more of classes because they can be reused and assigned to multiple elements.
However an id can belong to only one element at a time hence less of them.
Classes only appearing once:
Such cases like the one you identified, you may call them semantically incorrect as id is more appropriate choice for that but still it would work and it probably happens couple of times that we get to use class which only appearing once (may be while defining that class we are thinking that we can use it somewhere also but at the end we really dont), beside general habit another reason could be:
That class styling is also used somewhere else along with another class for e.g.:
.logo{
width:250px;
height:250px;
float:left;
}
.logo class is applied to logo <div class='logo'>...</div> But there is another element which also require same three properties of logo and some other also so one can reuse logo there also.
<div class='otherstyle logo'>...</div> this would apply the style of logo as well as otherstyle to it.
In some other words to sum it up. The cardinality of a class is 1...* so you can use it one and more than one time. But for id it is 1...1 you will and only use it only once.

Are the nested ids in css appropriate?

I've been trying to get my own opinion about this issue but could not, so decided to ask.
While it seems to be well-known that the id in html is created to represent the unique element on the page, my experience is that the amount of unique elements on the page is normally quite big, especially in the custom forms. Moreover a lot of unique elements on the page are nested.
Let's take just a simple structure like this:
#content
form#search-filters
#datepicker
#search-results
When it comes to styling this peace of code you have in general two approaches (I am using scss and so are the examples):
Organize it hierarchically, e.g.
#content {
columns(8, 12);
#search-filters {
#include search-filters;
etc.
Go with the plain declarations
#content {
columns(8, 12);
}
#search-fiters {
#include search-filters;
And from my opinion it is damn cooler to have it in the first way, while it's somehow against all the logic.
The question stays even worth with the contents of that #search-filters block, given as the example above. Let's say you've used some Rails scaffolding which generated the id's for each element of the form hosting the filters, and you want to refer to that id's to provide the styling as well.
You know the the element is unique and that it will be unique in any form which extends the search-filters mixin. So you want it to have the id.
But you have to give it a class to make it logically consistent.
What is your opinion about this issue?
P.S. I've tried to read the spec about whether there are some performance difference in these two cases, but it doesn't say anything:
http://www.w3.org/TR/css3-selectors/#class-html
You generally want to have id and class selectors that are not nested, because this gives you the best rendering performance. You can read this in great details at Googles Optimize browser rendering article.
In addition having no nested CSS selectors lowers the specificity and allows you to override it for specific cases more easily.
For simple sites that have a manageable amount of style this may not matter, especially if you also handle the other speed aspects right, like put styles before scripts. In such cases I would prefer the nested style for better readability.
I don't think nesting IDs selectors will make CSS styles apply faster from a browser rendering point of view.
Also, since you already have the ID, using only that ID will make your CSS more easy to read instead of having long selectors chain.
It is different though if you plan to have different styles referencing to the same element, if the element should change it's position along the page, or maybe removed and then later recreated in another position (thus needing different selectors). In this case maybe you will need to have nested selectors, otherwise I don't see the need for that.

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!

Is there any reason for including the tag name with a class or ID selector in CSS?

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.

Whats the difference between using .Class or #ElementId in CSS?

Ive been wondering... in CSS are there any differences between creating a style class and applying it an element, or creating a style with the #elementId notation (apart from being able to assign a class to different elements)?
For example...
#div1
{
background-color: Yellow;
}
<div id="div1">
Hello world!
</div>
Or
.div1
{
background-color: Yellow;
}
<div class="div1">
Hello world!
</div>
Thanks! :)
An ID must be unique in a document. Classes can be used in any number and combination. So you can use one class on multiple elements and multiple classes on one element.
One other difference; id-selectors are more specific than class-selectors, so I believe they will "trump" any other selector that exists. You can use "important" to do the same thing, but and id selector may be easier.
But id-selectors should be used sparingly...
Many classes can include a given "class" while only one element may be identified by a given ID. If you need to locate an unique Element use ID, otherwise if you wish to mark many elements that are basically the same but in different spots in your html use 'class'.
You sort of answered your own question, they are just mechanisms to 'identify' elements.
using #elementID applies only to the element uniquely identified by that id. a class can be used by multiple elements
there is however an order of precedence. selectors using the id have greater weight than selectors using class and when there is a collision the #id selector will take precedence
edit: see http://kiribao.blogspot.com/2008/03/css-selectors-precedence-and-ways-to.html for more detail on selector precedence
edit: also see the w3c specs at http://www.w3.org/TR/CSS21/cascade.html#specificity
Performance or functionality-wise, there is no difference [citation needed].
The only real difference is semantic, if you are working on a single node with a unique ID, or if you need a reusable class marking several nodes.
There are some differences:
Uniqueness
IDs must be unique, classes can be repeated. This is logical if you look at their expected usage.
Usage
IDs should be used to denote large sections of a website (e.g. #header), or unique elements that are accessed via Javascript (e.g. #killSession)
Classes should be used for reusable parts.
Specifity
IDs get assigned a specifity value of 100, while classes are only worth 1.
So this rule:
#id .class
Is worth 101 points.
This rule:
#id #id2
Is worth 200 points and will always trump the #id .class rule (regardless of the source order).
Performance
Performance wise, getting elements by ID is always faster than class, especially when talking Javascript. I'd love to see someone add some cold hard numbers to this.
Discussion
An interesting discussion about the performance of selectors can be found at Shaun Inman's blog.
The usage of classes is debated in Jeff Croft Applying OOP concepts to CSS
Classes are to group together elements which share similar functionality (for scripting) and/or layout (for styling). IDs should always be unique identifiers for elements.
A good example for something which should have an ID is the content area of your document, which is common to use the #content ID for. Classes are good for anything else which may occur twice in your document, such as headers which should have special markup or behavior, or links which should open a lightbox instead of the normal "go to URL" behavior.
HTH.