when to use Class selector and when to use ID selector [duplicate]
Possible Duplicate:
CSS: div id VS. div class
I am new to CSS and have general question: how do you decide wether it is better to use class selector or id selector?
The answers on this page are all good, but approach the difference from a more pragmatic point of view. Let me try an explain it to you from another point of view. The id you use when you define a conceptual entity of your page, for example a list of something, or a page footer or a navigational menu. Something of which you generally have merely one, as another wouldn't make sense or would be another type of entity. When you have a pattern of repeating entities, or element which serve the same purpose you tend to assign them a class, think about section headers, photos in a gallery etc. So the items in the previously mentioned list would all be assigned the same class name. Note though, that merely for styling reasons you could do with just classes, never use a single id, and be perfectly fine. It doesn't matter whether your class is used just once, or many times.
From the W3C standards an id should only be used once on a page, while a class can be used multiple times.
"ID" definition from http://www.w3schools.com/tags/att_standard_id.asp
The id attribute specifies a unique id for an HTML element. The id must be unique within the HTML document. The id attribute can be used by a JavaScript (via the HTML DOM) or by CSS to make changes or style the element with the specified id.
"Class" definition from http://www.w3schools.com/tags/att_standard_class.asp:
The class attribute specifies a classname for an element. The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class.
Since an id should be unique on the page it is also accessed A LOT faster through javascript
Id must be unique, class is not. So it depends on how you want to section the page.
id identifies uniquely an element, so you use it when you have only one element with it (ex ...
the class is applied to a group of elements with same features.
best practice says id is unique in the whole html page
ID's should be used for single elements:
<table id="specialtable">
Classes should be used for multiple elements:
<h3 class="awesomeheader"> <!-- an awesome header -->
<h2 class="awesomeheader"> <!-- another awesome header -->
It's good to use an id when you only have one item that you need to style for. Ex:
<div id = 'myDiv>Text</div>
#myDiv
{
display: block;
}
But when you have multiple items that you want to style the same way (say on multiple pages with css file for example) it is faster (and better) to use a class
<div class = "MyDiv> text </div>
<div class = "MyDiv> more text</div>
.MyDiv
{
color: black;
}
精彩评论