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.
Related
Sorry for this basic over asked question but I feel I have something to add.
I know id's are for elements which are only used once and classes are for elements which use it multiple times. But does this refer to a single page or the site as a whole?
i.e If I were using a wrapper called main-wrapper which is only used once in the page but on every page of the website would this be an id or a class? I've been making them classes throughout this project and am curious if I need to go back and change it all.
ID's and classes are not just about uniqueness and duplications. There is something called Specificity in CSS, so if you read more on specificity, it will say that ID declarations have more specificity score than class rules, thus, it is recommended to use classes wherever you can in your CSS and leave ID's for JavaScript actions.
Also, lets be clear here, CSS has nothing to do with ID duplication nor does HTML. It's JavaScript where you will find issues if you duplicate the ID in your HTML(DOM). So technically you can use duplicate ID's as they are just identifiers for that element(though, HTML validation will yell out an error), but it does cause an issue when you start using those ID's in JavaScript. (Now am not saying that you should use duplicate ID's but just clarifying the basics.)
Talking more over specificity,
#something {
color: red;
}
.something {
color: green;
}
<div class="something" id="something">This will be red and not green</div>
So, the more you make use of ID's, the more specific your CSS gets and at certain stage, you need to write even more specific rules to override the previous ones thus creating more messy CSS.
Base rule, use tag selectors wherever you can, atleast to set defaults or resetting those elements, use classes over ID's, leave ID's if you want initiate a particular EVENT or ACTION via JavaScript, for example, a click event on a button. Using ID's in your HTML helps JavaScript process faster as it will stop looking for another element beyond your first matched element.
In most cases things are referred to on a per page or per document basis.
No ID should be repeated on a single page of a web site. But it's is fine to use the same ID on every page of a site. So you can have a primary div with id="main_container" and use that on each page of your site. But it should only appear once on each page.
A "class" is designed to be used multiple times on each page or on an as-needed basis.
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
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.
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. :-)
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>