[INTRODUCTION] The ID selector ID selector can specify a specific style for HTML elements labeled with a specific ID. The ID selector is defined with "". The following two ID selectors, the first one can define the color of the element is red, the second defines the color of the element as green: Red {color:re
ID Selector
The ID selector can specify a specific style for an HTML element that is labeled with a specific ID.
The ID selector is defined as "#".
The following two ID selectors, the first one can define the color of the element to be red, 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 property of red is shown in red, and the P element with the id attribute green is shown in the blue.
<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. Want to know why, see XHTML: Site refactoring.
ID selector and Derivation selector
In modern layouts, ID selectors are often used to establish derived selectors.
#sidebar p {
Font-style:italic;
Text-align:right;
Margin-top:0.5em;
}
The above style will only apply to paragraphs that appear in an element with an ID of sidebar. This element is most likely a p 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 this usage is illegal because it is not possible to embed <p> in inline element <span> (If you forget the reason, see XHTML: Site refactoring).
A selector, multiple usages
This ID selector can be used many times as a derived selector, even if the element labeled Sidebar only appears 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;
}
In this case, unlike other p elements in the page, the P element in the sidebar is handled in a special context, and, unlike all the other H2 elements on the page, the H2 elements in the sidebar are treated differently.
Separate selector
The ID selector can work independently even if it is not used to create a derived selector:
#sidebar {
border:1px dotted #000;
padding:10px;
}
According to this rule, an element with ID sidebar will have a pixel-wide black dot border with a width of 10 pixels (padding, internal whitespace) around it. Older versions of the Windows/ie browser may ignore this rule unless you specifically define the element to which this selector belongs:
P#sidebar {
border:1px dotted #000;
padding:10px;
}