Id Selector
The id selector can specify a specific style for HTML elements labeled with a specific id.
The id selector is defined.
The following two id selectors can be used to define the color of the first element as red, and the color of the second element as Green:
# Red {color: red ;}
# Green {color: green ;}
In the following HTML code, the p element whose id attribute is red is displayed in red, while the p element whose id attribute is green is displayed in green.
<P id = "red"> the paragraph is red. </P>
<P id = "green"> This section is green. </P>
Note: The id attribute can only appear once in each HTML document. For the reason, see XHTML: website reconstruction.
Id selector and derived Selector
In modern la S, the id selector is often used to create a derived selector.
# Sidebar p {
Font-style: italic;
Text-align: right;
Margin-top: 0.5em;
}
The above style will only apply to paragraphs that appear in the element where id is sidebar. This element may be a div or table unit, 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>. However, this method is invalid, because <p> cannot be embedded in the inline element <span> (if you forget the reason, see XHTML: website reconstruction ).
One selector for multiple usage
Even if the element labeled as sidebar appears only once in the document, this id selector can be used many times as a derived selector:
# 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 other p elements on the page, the p elements in the sidebar get special processing, and, unlike all other h2 elements on the page, the h2 elements in the sidebar get different special processing.
Separate Selector
The id selector can be used independently even if it is not used to create a derived selector:
# Sidebar {
Border: 1px dotted #000;
Padding: 10px;
}
According to this rule, the element with the id of sidebar will have a black dot border with a pixel width, and there will be a 10 pixel width padding (padding, internal blank) around it ). Earlier versions of Windows/IE may ignore this rule unless you specifically define the elements to which this selector belongs:
Div # sidebar {
Border: 1px dotted #000;
Padding: 10px;
}