Core tip:The ID selector can specify a specific style for HTML elements marked with a specific ID.
ID Selector
The ID selector can specify a specific style for HTML elements marked with a specific ID.
The ID selector is defined with "#".
The following two ID selectors, the first one to define the color of the element is red, and the second defines the color of the element as green:
#red {color:red;}
#green {color:green;}
In the following HTML code, the P element with the id attribute of red is displayed in red, and a P element with the ID property is green.
<p id= "Red" > This paragraph is red. </p>
<p id= "Green" > This paragraph is greenish. </p>
Note: The id attribute can only appear once in each HTML document. Do you want to know why, see XHTML: Web site refactoring.
ID selector and Derivation selector
In modern layouts, ID selectors are often used to establish derivation selectors.
#sidebar p {
Font-style:italic;
Text-align:right;
Margin-top:0.5em;
}
The above style applies only to paragraphs that appear within an element with ID sidebar. This element is probably a div or a table cell, although it may also be a table or other block-level element. It can even be an inline element, such as <em></em> or <SPAN></SPAN>, but such usage is illegal because it is not possible to embed <p> in inline element <span> (If you forget why, see XHTML: Web Refactoring).
A selector, multiple usages
This ID selector can be used many times as a derivation selector, even if the element that is marked as sidebar only occurs once in the document:
#sidebar p {
Font-style:italic;
Text-align:right;
Margin-top:0.5em;
}
#sidebar H2 {
Font-size:1em;
Font-weight:normal;
Font-style:italic;
margin:0;
line-height:1.5;
Text-align:right;
}
Here, unlike the other P elements in the page, the P element in the sidebar gets a special deal, and the H2 elements in the sidebar are also treated differently than any other H2 element in the page.
A separate selector
An ID selector can work independently, even if it is not used to create a derivation selector:
#sidebar {
border:1px dotted #000;
padding:10px;
}
According to this rule, an element with an ID of sidebar will have a black dotted border with a pixel width, with an internal margin of 10 pixels wide (padding, inner space) around it. Older versions of Windows/ie browsers may ignore this rule unless you specifically define the element to which this selector belongs:
Div#sidebar {
border:1px dotted #000;
padding:10px;
}