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

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

Related

Difference in Class and ID for CSS

Okay, so I understand how to use both, but really what is the point other than semantics? I mean, what negative effect would it have if I created a class for a single, unique, element and only used it on that element?
Also, I know you can assign only certain elements to be effected by a class, for instance:
p.class{blazziblazzi}
Now, only the element 'p' will be effect by that class, if that element is assigned to that class. So why would anybody ever assign that class to an element if they didn't want that element to take on the attributes of that class?
I just don't get why they even made ID and Class separate, it seems pointless to me.
Any pointers would help, thanks!
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.
http://css-tricks.com/the-difference-between-id-and-class/
Classes should not use it to rewrite code, I mean you must avoid writing the same, then for that you use a class, instead of assigning each id the same attributes.
For example:
If you have two elements:
<div id="div1" class="divYellow">
</div>
<div id="div2" class="divYellow">
</div>
if you want yellow background color, you could do so:
# div1
{
background-color: yellow;
}
\# div2
{
background-color: yellow;
}
but it would be best that you did so:
. divYellow
{
background-color: yellow;
}
This way when you want to make a change, you just do it in class, and not in two places
Specificity is one of the reasons. You can follow the link in the comments for info on that. Additionally, when you need to add anchor links, you have to use id's, classes will not work. Also, id's are particularly useful for specifying items while using javascript and other languages. In CSS, there is no harm in specifying a class for a single item, but it is a better practice to use id's for unique elements and classes for elements that may mimic the styles of other elements.
if using an ID will stop at the first occurrence.
If it is a class, it will scan the entirety of the document to make sure there aren't other occurrences.
Even if there is 1 occurance of a class, it still needs to scan the entire document to make sure there are none. It leads to issues with selection and runtime of fetching data, given various selectors.
U could for example shorten your CSS. By using a classname multiple times you could save some lines inside your CSS. I would only recommend this if you want to use a large part of your CSS for multiple div's. The small changes could be made within the different ID's if the classnames remain the same.

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

What is the difference between id and class in CSS, and when should I use them? [duplicate]

This question already has answers here:
What's the difference between an id and a class?
(17 answers)
Closed 5 years ago.
#main {
background: #000;
border: 1px solid #AAAAAA;
padding: 10px;
color: #fff;
width: 100px;
}
<div id="main">
Welcome
</div>
Here I gave an id to the div element and it's applying the relevant CSS for it.
OR
.main {
background: #000;
border: 1px solid #AAAAAA;
padding: 10px;
color: #fff;
width: 100px;
}
<div class="main">
Welcome
</div>
Now here I gave a class to the div and it's also doing the same job for me.
Then what is the exact difference between Id and class and when should I use id and when should I use class.? I am a newbie in CSS and Web-design and a little bit confused while dealing with this.
Use a class when you want to consistently style multiple elements throughout the page/site. Classes are useful when you have, or possibly will have in the future, more than one element that shares the same style. An example may be a div of "comments" or a certain list style to use for related links.
Additionally, a given element can have more than one class associated with it, while an element can only have one id. For example, you can give a div two classes whose styles will both take effect.
Furthermore, note that classes are often used to define behavioral styles in addition to visual ones. For example, the jQuery form validator plugin heavily uses classes to define the validation behavior of elements (e.g. required or not, or defining the type of input format)
Examples of class names are: tag, comment, toolbar-button, warning-message, or email.
Use the ID when you have a single element on the page that will take the style. Remember that IDs must be unique. In your case this may be the correct option, as there presumably will only be one "main" div on the page.
Examples of ids are: main-content, header, footer, or left-sidebar.
A good way to remember this is a class is a type of item and the id is the unique name of an item on the page.
ids 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.
Javascript cares
JavaScript people are already probably more in tune with the differences between classes and ids. JavaScript depends on there being only one page element with any particular id, or else the commonly used getElementById function couldn't be depended on.
For more info on this click here.
Example
<div id="header_id" class="header_class">Text</div>
#header_id {font-color:#fff}
.header_class {font-color:#000}
(Note that CSS uses the prefix # for IDs and . for Classes.)
However color was an HTML 4.01 <font> tag attribute deprecated in HTML 5.
In CSS there is no "font-color", the style is color so the above should read:
Example
<div id="header_id" class="header_class">Text</div>
#header_id {color:#fff}
.header_class {color:#000}
The text would be white.
IDs must be unique--you can't have more than one element with the same ID in an html document. Classes can be used for multiple elements. In this case, you would want to use an ID for "main" because it's (presumably) unique--it's the "main" div that serves as a container for your other content and there will only be one.
If you have a bunch of menu buttons or some other element for which you want the styling repeated, you would assign them all to the same class and then style that class.
As pretty much everyone else has said use ID for one-off elements and class for multiple use elements.
Here is a quick, over simplified example, take HTML and HEAD tags as read
<body>
<div id="leftCol">
You will only have one left column
</div>
<div id="mainContent">
Only one main content container, but.....
<p class="prettyPara">You might want more than one pretty paragraph</p>
<p>This one is boring and unstyled</p>
<p class="prettyPara">See I told you, you might need another!</p>
</div>
<div id="footer">
Not very HTML5 but you'll likely only have one of these too.
</div>
</body>
Also, as mentioned in other answers ID are well exposed to javascript, classes less so. However modern javascript frameworks like jQuery leverage class for javascript too
ID's have the functionality to work as links to particular sections within a webpage.
a keyword after # tag will take you to a particular section of the webpage.
e.g "http://exampleurl.com#chapter5" in the address bar will take you there when you have a "section5" id wrapped around the chapter 5 section of the page.
The class attribute can be used with multiple HTML elements/tags and all will take the effect. Where as the id is meant for a single element/tag and is considered unique.
Moreoever the id has a higher specificity value than the class.
id:
It will identify the unique element of your entire page. No other element should be declared with the same id.
The id selector is used to specify a style for a single, unique element.
The id selector uses the id attribute of the HTML element, and is defined with a "#".
class:
The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
If there is something to add to the previous good answers, it is to explain why ids must be unique per page. This is important to understand for a beginner because applying the same id to multiple elements within the same page will not trigger any error and rather has the same effects as a class.
So from an HTML/CSS perspective, the uniqueness of id per page does not make a sens. But from the JavaScript perspective, it is important to have one id per element per page because getElementById() identifies, as its name suggests, elements by their ids.
So even if you are a pure HTML/CSS developer, you must respect the uniqueness aspect of ids per page for two good reasons:
Clarity: whenever you see an id you are sure it does not exist elsewhere within the same page
Scalability: Even if you are developing only in HTML/CSS, you need to take in consideration the day where you or an other developer will move on to maintain and add functionality to your website in JavaScript.
You can assign a class to many elements. You can also assign more than one class to an element, eg.
<button class="btn span4" ..>
in Bootstrap. You can assign the id only to one.
So if you want to make many elements look the same, eg. list items, you choose class. If you want to trigger certain actions on an element using JavaScript you will probably use id.
A class can be used several times, while an ID can only be used once, so you should use classes for items that you know you're going to use a lot. An example would be if you wanted to give all the paragraphs on your webpage the same styling, you would use classes.
Standards specify that any given ID name can only be referenced once within a page or document. Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.
This is very simple to understand :-
id is used when we have to apply CSS property to one attribute only.
class is used when we have to use CSS property in many locations within the same page or different.
General :- for unique structure like staring div and buttons layout we use id .
for same CSS throughout the page or project we use class
id is light and class is little heavy
A simple way to look at it is that an id is unique to only one element.
A class is not unique and applied to multiple elements.
For example:
<p class = "content">This is some random <strong id="veryImportant"> stuff!</strong></p>
Content is a class since it'll probably apply to some other tags aswell where as "veryImportant" is only being used once and never again.
Unlike the id selector, the class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
A simple way to look at it is that an id is unique to only one element. class is better to use as it will help you to execute what ever you want.
id selector can be used to more elements. here is the example:
css:
#t_color{
color: red;
}
#f_style{
font-family: arial;
font-size: 20px;
}
html:
<p id="t_color"> test only </p>
<div id="t_color">the box text</div>
I tested on internet explorer (ver. 11.0) and Chrome (ver.47.0). it works on both of them.
The "unique" only means one element can not have more than one id attributes like class selector. Neither
<p id="t_color f_style">...</p>
nor
<p id="t_color" id="f_style">...</p>

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.