3.12 關於 Pseudo Class
用途:為一個元素,定義不同的狀態,然後套用樣式。
語法
selector:pseudo-class {
property:value;
}
:root
指的就是 html 元素:
:root{
background-color: red;
}
/* 等同於 */
html{
background-color: red;
}
但還是有所差別,即 :root
的優先權是高於 html 的。也就是說,以下的 CSS,背景色會是 :root
所指定的顏色。
html{
background-color: yellow;
}
:root{
background-color: red; /* 這個會被套用 */
}
例:
:hover
滑鼠移過後會套用:
p:hover{
color: blue;
font-size: 20px;
}
:first-child
相對於父元素,第一個子元素會套用:
p:first-child{
color: blue;
font-size: 20px;
}
:last-child
相對於父元素,最後一個子元素會套用:
p:last-child{
color: blue;
font-size: 20px;
}
:nth-child
相對於父元素,指定第幾個子元素會套用:
p:nth-child(2){
color: blue;
font-size: 20px;
}
n 從 0 開始依序代入,0、1、2、3 這樣的方式:(例:奇數個套用到)
p:nth-child(2n+1){
color: blue;
font-size: 20px;
}
:focus
元素有 focus 狀態的時候會套用到:
input:focus {
background-color: yellow;
}
:checked
欄位被勾選的狀態時,會套用到
input:checked + label{
color: red;
}
:disabled 及 :read-only
/* 只會套用到屬性有 disabled 的 input 標籤 */
input:disabled{
border: 1px solid blue;
color: white;
background-color: gray;
}
/* 會套用到屬性有 disabled 及 readonly 的 input 標籤 */
input:read-only{
border: 1px solid red;
color: black;
background-color: lightgray;
}
例:
其它資源
CSS Pseudo-classes