DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS進階教程
CSS語法入門:選擇器、屬性與值怎麼組
編輯:CSS進階教程     

基本語法

一條CSS規則由三個部分組成:選擇器(selector)、屬性(property)與值(value)。

selector { property: value }

選擇器通常就是你想定義的HTML元素或標籤,屬性是你想改動的那個特性,每個屬性都有一個對應的值。屬性與值之間用冒號隔開,整組宣告則包在左右大括號裡:

body { color: black }

注意:如果值是由多個單字組成,記得加上引號:

p { font-family: "sans serif" }

注意:要一次指定多個屬性,屬性之間必須用分號隔開。例如把段落設為置中、文字為紅色:

p { text-align: center; color: red }

為了讓樣式定義更好讀,也可以一個屬性一行:

p
{
    text-align: center;
    color: black;
    font-family: arial
}

群組(Grouping)

多個選擇器可以合併成一個群組,彼此用逗號隔開。下面的例子把所有標題元素歸在同一組,讓它們都變成綠色文字:

h1, h2, h3, h4, h5, h6
{
    color: green
}

class 選擇器

用 class 選擇器,你可以替同一種HTML元素定義出不同的樣子。假設文件裡需要兩種段落,一種靠右對齊、一種置中:

p.right  { text-align: right }
p.center { text-align: center }

接著在HTML中用 class 屬性指定:

<p class="right">This paragraph will be right-aligned.</p>
<p class="center">This paragraph will be center-aligned.</p>

注意:一個元素要套用多個 class,語法如下:

<p class="center bold">This is a paragraph.</p>

上面這個段落會同時受到 "center" 與 "bold" 兩個 class 的影響。

你也可以把標籤名稱從選擇器中省略,定義一個「只要掛上這個 class 就生效」的通用樣式。下面的寫法會讓所有 class="center" 的元素都置中:

.center { text-align: center }

在下面的程式碼中,h1 與 p 都掛了 class="center",因此兩者都會套用 .center 的規則:

<h1 class="center">This heading will be center-aligned</h1>
<p class="center">This paragraph will also be center-aligned.</p>

另外請不要用數字開頭當作 class 名稱,這只有 Internet Explorer 吃得下去。


針對特定屬性套用樣式

CSS也能依據元素的屬性來選取。下面這條規則會命中所有 type 屬性值為 "text" 的 input 元素:

input[type="text"] { background-color: blue }

id 選擇器

id 選擇器以井字號(#)表示,同樣可以替元素定義樣式。這條規則會命中 id 值為 "green" 的元素:

#green { color: green }

而這條規則只會命中 id 為 "para1" 的 p 元素:

p#para1
{
    text-align: center;
    color: red
}

同樣地,不要用數字開頭當作 id 名稱,否則在 Mozilla/Firefox 中不會生效。


CSS 註解

註解是用來解釋程式碼的,之後回頭修改原始碼時會輕鬆很多,而瀏覽器會直接忽略它們。CSS 註解以 /* 開始、以 */ 結束:

/* This is a comment */
p
{
    text-align: center;
    /* This is another comment */
    color: black;
    font-family: arial
}
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved