CSS ID Selector
- Previous Page CSS Derived Selector
- Next Page CSS Class Selector
id 选择器
id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式。
id 选择器以 "#" 来定义。
下面的两个 id 选择器,第一个可以定义元素的颜色为红色,第二个定义元素的颜色为绿色:
#red {color:red;} #green {color:green;}
下面的 HTML 代码中,id 属性为 red 的 p 元素显示为红色,而 id 属性为 green 的 p 元素显示为绿色。
id="red">这个段落是红色。
id="green">这个段落是绿色。
注意:id 属性只能在每个 HTML 文档中出现一次。想知道原因吗,请参阅 XHTML: Tsarin tattara shayi.
id 选择器和派生选择器
在现代布局中,id 选择器常常用于建立派生选择器。
#sidebar p { font-style: italic; text-align: right; margin-top: 0.5em; }
上面的样式只会应用于出现在 id 是 sidebar 的元素内的段落。这个元素很可能是 div 或者是表格单元,尽管它也可能是一个表格或者其他块级元素。它甚至可以是一个内联元素,比如 或者 ,不过这样的用法是非法的,因为不可以在内联元素 中嵌入 (如果你忘记了原因,请参阅 XHTML: Tsarin tattara shayi)。 Kamarin ba a yiya a kan kuma sidebar, abin da zai iya yin shi ne kuma yana iya yin shi kamar yadda ake amfani da shi: Here, the p elements inside sidebar are treated specially, which is clearly different from other p elements on the page, and the h2 elements inside sidebar are also treated differently, which is clearly different from all other h2 elements on the page.Maiwada: Sauyi wanda zai iya amfani da shi
#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;
}
Single Selector
Even if the ID selector is not used to create derived selectors, 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 it will also have a 10-pixel wide inner padding (padding, internal blank). 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