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

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.

Related

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

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).

what is the difference between (div#container) and (#container) in css

It's well known that the id should be unique in html tags, so it can be referenced directly using:
#container
However I noticed that some developer will prefix it with the tag name like this:
div#container
Now is there a difference? Is it related to performance? Or is it best practice conventions? Or for easy code readability?
div#container will ensure you only select the element if it is a div. Without the type selector, any element with that ID will be targeted. The type selector also adds specificity, but that's a minor thing.
Assuming you're following best practices and making sure your IDs are unique per page, you generally don't need to overqualify your ID selectors; having #container should be enough. But if you have a very good reason to distinguish the element type, there are no rules preventing you from doing that (although frankly, given the whole nature of IDs, I don't see why the same ID should ever be assigned to different types of elements altogether).
The basic difference is that with div#container you may not target an element although there is an element with id=container. For example if you have
<div id="container"></div>
then both will point the same element. But if you have
<p id="container"></p>
Then only the selector #container will target it. The selector div#container will not
The difference between div#container and #container is that
#container will only apply to element that has id="container"
While,
div#container will only apply to DIV that has an id="container"
Although you it is considered best practice to only use an id once. And if you need to use certain CSS again, might as well use class.
In html you may have a lot of other elements, such as span, table, etc, which may have the same id, for example "container". So this code:
#container: {....}
is a reference to all of them.
But when you write this:
div#container: {...}
You refer in a specific subcategory of those items. Also you may have a lot of divs. By this reference above, you target in a specific subcategory of divs elements.
Ok I asked this question with a wrong assumptions as follow:
There will be only one HTM page, hence:
There should be only one ID (container)
There will be an internal CSS block for such page
Based on the above wrong assumptions, it's needless to include the tag name.
However, the correct assumptions should be:
You have a website with multiple pages
Although id(container) is unique in every page, however it might be assigned to different elements, e.g. div id="conainer" in one page. And p id="container" in another page
most probably there is an external css file or is file that serves all these pages.
Its based on those assumptions the benefit of being more specific prefixing the tag name will prevent abnormal behavior
This is almost the same answer of laaposto

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.

Is using classes to a single element over an ID just a preference or there would be a complication to it?

In CSS I understand that you use ID if you're targeting a unique element and use classes for general targeting of a group of element. I am maintaining a site where i have to clean up some of the code (html + css), I notice that the previous programmer didn't use any ID for all the element instead he used classes even for unique elements.
So, what's should be an advisable approach, Should I just use classes and follow his coding style, avoid using ID for the elements or should I replace them with IDs and use ID for appropriate elements.
In css, in my understanding, classes can also be used like an ID where you can just target a single element (eg. .footer vs #footer) and is just a matter of preference.
#header { background: #ccc; height: 150px; }
#content { background: red; height: 200px; color: #fff; }
<div id="header"><h1>Header Area</h1></div>
<div id="content"><h1>Content</h1></div>
<div id="header"><h1>Footer Area</h1></div>
notice #header was mentioned twice in the id and css rule applies to the two elements.
IDs behaves like Classes (http://jsfiddle.net/79GsY/)
.header { background: #ccc; height: 150px; }
.content { background: red; height: 200px; color: #fff; }
.footer { background: brown; height: 150px; }
<div class="header"><h1>Header Area</h1></div>
<div class="content"><h1>Content</h1></div>
<div class="footer"><h1>Footer Area</h1></div>
Notice that there was no ID used here.
Classes behaves like ID (http://jsfiddle.net/qHEJd/)
Please enlighten me with this matter. Thank You.
It's a matter of semantics. You use IDs to identify an element, for instance to distinguish multiple forms on a page, or as link targets. They have a meaning to the markup.
With classes, you set a classification for things, you don't really give them a meaning. It's not like you're grouping them together or anything.
So it's perfectly fine if only one element on a page has a certain class. That doesn't make it "unique".
An ID must be unique, a class can be used several times.
Personally I use IDs to name different sections of a site. IDs always describe what something is, never what it looks like. Examples of common IDs for me are #header, #footer, #post-comment etc.
Classes, on the other hand, are used to categorise similar elements. Both CSS and JS can then target a specific class. Examples of classes are .button, .icon etc.
Personally I don't use classes much at all but prefer to use SASS #mixins as they keep the HTML clean from design related class names.
In this instance, there's very little difference between using class names or ID. There is argument that using an ID in CSS will allow for minutely-faster processing, but it's such a tiny difference to be negligible.
There isn't any reason why you should spend the time modifying the previous developer's markup as long as it is valid (ie: no repetition of IDs) and works. Modifying classes or IDs/etc may well cause non-desired effects (particularly if the JavaScript is tied to those same DOM elements).
The only difference when it matters if you use class or id is if you multiple instances of that element. Say, you had a header/content and footer, you know you're going to have only singleton instances of these and so I'd use an id.
However, if you have two headers, so:
<div id="header></div>
<div id="header></div>
This does not comply with HTML standards, and so I'd use:
<div class="header></div>
<div class="header></div>
In base, if it's a single instance of that element, use an id. If you know you're doing the same operation more than once on an element, use a class. This is also the standard rule for CSS, to a degree.
You should always keep in mind that ID's Should be unique , if you have unique element, you better use ID, if not use class
quoting from w3c page -
What makes attributes of type ID special is that no two such
attributes can have the same value in a document
http://www.w3.org/wiki/CSS/Selectors/id_selector
I would prefer to use ID for the Unique element and Classes for the group of element.
Because,
When you are using IDs for the unique element DOM will search Tag with tha ID and will stop its searching as soon as it finds that Tag.
On the other end if you choose class for the unique element it would work same as IDS but DOM will not stop its searching even after it finds that Tag. It will search the whole page to find any other Tag with that class.
For the Group of Elements, we can't use IDS hence the using Class is the obvious Choice.
Hope this clear your doubt. Let me know if i am missing something.
The odds of it making any real difference to the site are near zero, so it's up to you. It's a style preference.
I think your question is mainly about the application of CSS styles to the elements, as opposed to scripting. When the CSS is being applied to the elements for styling purposes, I believe it makes literally no difference (other than specificity stuff) whether you use class selectors or ID selectors to specify the styles for the elements. Style application is done by taking the element and matching it against rules, not taking rules and finding elements that match them, if you see what I mean.
On the scripting front, though, for completeness: If you're looking up these elements with jQuery using CSS selectors, an ID selector may be very marginally faster than a class selector to find a single element in a very large document. That's because $("#someId") ends up being a call to document.getElementById which the browser can do efficiently because it knows that there will only be a single match. In contrast, $(".someClass") ends up being a call to querySelectorAll, which has to keep searching through the entire document (barring that search having already been cached by the selector engine, of course) even after finding one element, in case there are others.
But again: The odds of it making any real-world difference are virtually nil.
And a very minor point: Every element with an id creates a property on the window object with that id as its name (e.g., <div id="foo"> creates a foo property on window). Creating a lot of properties you're not going to use is a teensy tiny ipsy little bit of unnecessary work. ;-) But to call that premature optimization is to dramatically underestimate how premature it is (and dramatically overestimate the amount it optimizes). E.g., this is just trivia. :-)

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.