css中類別選取器是如何使用的執行個體詳解

來源:互聯網
上載者:User
在css中類別選取器就是在類名前面加一個點號了,如果是多類不是打多個點號而以.important.urgent這種形式了。

類別選取器
在 CSS 中,類別選取器以一個點號顯示:

    .center {text-align: center}

在上面的例子中,所有擁有 center 類的 HTML 元素均為置中。
在下面的 HTML 程式碼中,h1 和 p 元素都有 center 類。這意味著兩者都將遵守 ".center" 選取器中的規則。

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

注意:類名的第一個字元不能使用數字!它無法在 Mozilla 或 Firefox 中起作用。
和 id 一樣,class 也可被用作派生選取器:

 .fancy td {         color: #f60;         background: #666;         }

在上面這個例子中,類名為 fancy 的更大的元素內部的表格單元都會以灰色背景顯示橙色文字。(名為 fancy 的更大的元素可能是一個表格或者一個 p)
元素也可以基於它們的類而被選擇:

    td.fancy {         color: #f60;         background: #666;         }

在上面的例子中,類名為 fancy 的表格單元將是帶有灰色背景的橙色。

   <td class="fancy">

多類別選取器

1、在 HTML 中,一個 class 值中可能包含一個詞列表,各個詞之間用空格分隔。例如,如果希望將一個特定的元素同時標記為重要(important)和警告(warning),就可以寫作(這兩個詞的順序無關緊要,寫成 warning important 也可以):

<p class="important warning">This paragraph is a very important warning.</p>

我們假設 class 為 important 的所有元素都是粗體,而 class 為 warning 的所有元素為斜體,class 中同時包含 important 和 warning 的所有元素還有一個銀色的背景 。就可以寫作:

.important {font-weight:bold;}.warning {font-weight:italic;}.important.warning {background:silver;}

2、通過把兩個類別選取器連結在一起,僅可以選擇同時包含這些類名的元素(類名的順序不限)。
如果一個多類別選取器包含類名列表中沒有的一個類名,匹配就會失敗。請看下面的規則:

.important.urgent {background:silver;}

不出所料,這個選取器將只匹配 class 屬性中包含詞 important 和 urgent 的 p 元素。因此,如果一個 p 元素的 class 屬性中只有詞 important 和 warning,將不能匹配。不過,它能匹配以下元素:

<p class="important urgent warning">This paragraph is a very important and urgent warning.</p>
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.