Manual Dalam Talian CSS
/ CSS Id 和 Class
CSS Id 和 Class
id 和 class 選擇器
如果你要在HTML元素中設(shè)置CSS樣式,你需要在元素中設(shè)置"id" 和 "class"選擇器。
id 選擇器
id 選擇器可以為標(biāo)有特定 id 的 HTML 元素指定特定的樣式。
HTML元素以id屬性來設(shè)置id選擇器,CSS 中 id 選擇器以 "#" 來定義。
以下的樣式規(guī)則應(yīng)用于元素屬性 id="para1":
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <style> .center { text-align:center; } </style> </head> <body> <h1 class="center">標(biāo)題居中</h1> <p class="center">段落居中。</p> </body> </html>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
ID屬性不要以數(shù)字開頭,數(shù)字開頭的ID在 Mozilla/Firefox 瀏覽器中不起作用。
class 選擇器
class 選擇器用于描述一組元素的樣式,class 選擇器有別于id選擇器,class可以在多個元素中使用。
class 選擇器在HTML中以class屬性表示, 在 CSS 中,類選擇器以一個點(diǎn)"."號顯示:
在以下的例子中,所有擁有 center 類的 HTML 元素均為居中。
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <style> .center { text-align:center; } </style> </head> <body> <h1 class="center">標(biāo)題居中</h1> <p class="center">段落居中。</p> </body> </html>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
你也可以指定特定的HTML元素使用class。
在以下實(shí)例中, 所有的 p 元素使用 class="center" 讓該元素的文本居中:
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <style> p.center { text-align:center; } </style> </head> <body> <h1 class="center">This heading will not be affected</h1> <p class="center">This paragraph will be center-aligned.</p> </body> </html>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
類名的第一個字符不能使用數(shù)字!它無法在 Mozilla 或 Firefox 中起作用。