CSS 屬性選擇器 (Attribute Selectors)
屬性選擇器可以根據 HTML 元素的屬性或屬性值來選取元素。
[attr] - 存在屬性
選取帶有指定屬性的元素,不管屬性值是什麼。
[disabled] {
opacity: 0.5;
}
<button disabled>這個按鈕會被選取</button> <button>這個按鈕不會被選取</button>
[attr="value"] - 完全相等
選取屬性值完全等於指定值的元素。
[type='text'] {
border: 1px solid gray;
}
<input type="text" />
<!-- 會被選取 -->
<input type="email" />
<!-- 不會被選取 -->
[attr~="value"] - 包含單詞
選取屬性值中包含指定「單詞」的元素(以空格分隔的單詞列表)。
[class~='warning'] {
color: red;
}
<p class="warning">會被選取</p>
<p class="warning message">會被選取</p>
<p class="warning-text">不會被選取(warning-text 不是獨立單詞)</p>
[attr|="value"] - 開頭相等或前綴
選取屬性值等於指定值,或以指定值開頭且後面接著連字號 - 的元素。常用於選取語言屬性。
[lang|='en'] {
font-family: Arial, sans-serif;
}
<p lang="en">會被選取</p>
<p lang="en-US">會被選取</p>
<p lang="en-GB">會被選取</p>
<p lang="english">不會被選取</p>
[attr^="value"] - 開頭符合
選取屬性值以指定字串「開頭」的元素。
[href^='https'] {
color: green;
}
<a href="https://example.com">會被選取(https 開頭)</a> <a href="http://example.com">不會被選取</a>
[attr$="value"] - 結尾符合
選取屬性值以指定字串「結尾」的元素。
[href$='.pdf'] {
color: red;
}
<a href="document.pdf">會被選取(.pdf 結尾)</a> <a href="document.doc">不會被選取</a>
[attr*="value"] - 包含字串
選取屬性值中「包含」指定字串的元素。
[href*='example'] {
text-decoration: underline;
}
<a href="https://example.com">會被選取</a>
<a href="https://www.example.org/page">會被選取</a>
<a href="https://google.com">不會被選取</a>
大小寫不敏感
在屬性選擇器的結尾加上 i,可以讓比對不區分大小寫。
[type='text' i] {
border: 1px solid blue;
}
<input type="TEXT" />
<!-- 會被選取 -->
<input type="Text" />
<!-- 會被選取 -->
<input type="text" />
<!-- 會被選取 -->
屬性選擇器總覽
| 選擇器 | 說明 |
|---|---|
[attr] | 有該屬性 |
[attr="value"] | 屬性值完全等於 value |
[attr~="value"] | 屬性值包含 value 這個單詞 |
[attr|="value"] | 屬性值等於 value 或以 value- 開頭 |
[attr^="value"] | 屬性值以 value 開頭 |
[attr$="value"] | 屬性值以 value 結尾 |
[attr*="value"] | 屬性值包含 value 字串 |
實際應用範例
外部連結樣式
/* 外部連結加上特殊樣式 */
a[href^='http'] {
padding-right: 20px;
background: url('external-link-icon.png') right center no-repeat;
}
/* 但排除自己網站的連結 */
a[href^='https://mysite.com'] {
padding-right: 0;
background: none;
}
檔案類型圖示
a[href$='.pdf']::before {
content: '📄 ';
}
a[href$='.zip']::before {
content: '📦 ';
}
a[href$='.jpg']::before,
a[href$='.png']::before {
content: '🖼️ ';
}
表單輸入框樣式
input[type='text'],
input[type='email'],
input[type='password'] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type='submit'] {
background-color: blue;
color: white;
cursor: pointer;
}