CSS ID Selector
- Previous Page CSS Derived Selector
- Next Page CSS Class Selector
ID selectors
ID selectors can specify specific styles for HTML elements with specific ids.
ID selectors are defined by "#".
The following two id selectors, the first can define the color of the element as 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 an id attribute of red is displayed in red, while the p element with an id attribute of green is displayed in green.
<p id="red">This paragraph is red.</p> <p id="green">This paragraph is green.</p>
Note:The id attribute can only appear once in each HTML document. Want to know the reason? Please refer to XHTML: website reconstruction.
ID selectors and descendant selectors
In modern layouts, id selectors are often used to establish descendant selectors.
#sidebar p { font-style: italic; text-align: right; margin-top: 0.5em; }
The above styles will only be applied to paragraphs within elements with an id of sidebar. This element is likely to be 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>, although such usage is illegal because <p> cannot be embedded within an inline element <span> (if you forget the reason, please refer to XHTML: website reconstruction)
One selector, multiple uses
Even if the elements marked as sidebar can only appear once in the document, this id selector as a descendant selector can be used many times:
#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, the p elements inside sidebar are treated differently from other p elements on the page, and the h2 elements inside sidebar are also treated differently from other h2 elements on the page.
Single Selector
Even if the ID selector is not used to create a derived selector, it can still work independently:
#sidebar { border: 1px dotted #000; padding: 10px; }
According to this rule, the element with id 'sidebar' will have a black dotted border one pixel wide, and there will be a 10-pixel wide padding (padding, internal blank) 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; }
Related Content
If you need to learn more about ID selectors, please read the advanced tutorial on CodeW3C.com:CSS ID Selector Detail.
- Previous Page CSS Derived Selector
- Next Page CSS Class Selector