用途:為一個元素,定義不同的狀態,然後套用樣式。
selector:pseudo-class {
property:value;
}
指的就是 html 元素:
:root{
background-color: red;
}
/* 等同於 */
html{
background-color: red;
}
但還是有所差別,即 :root
的優先權是高於 html 的。也就是說,以下的 CSS,背景色會是 :root
所指定的顏色。
html{
background-color: yellow;
}
:root{
background-color: red; /* 這個會被套用 */
}
例:
{% embed url="https://codepen.io/carlos411/pen/rNxyrzy" %}
滑鼠移過後會套用:
p:hover{
color: blue;
font-size: 20px;
}
{% embed url="https://codepen.io/carlos411/pen/LYPjgQV" %}
相對於父元素,第一個子元素會套用:
p:first-child{
color: blue;
font-size: 20px;
}
{% embed url="https://codepen.io/carlos411/pen/wvwqYyP" %}
相對於父元素,最後一個子元素會套用:
p:last-child{
color: blue;
font-size: 20px;
}
{% embed url="https://codepen.io/carlos411/pen/XWraxZQ" %}
相對於父元素,指定第幾個子元素會套用:
p:nth-child(2){
color: blue;
font-size: 20px;
}
{% embed url="https://codepen.io/carlos411/pen/oNveaqj" %}
n 從 0 開始依序代入,0、1、2、3 這樣的方式:(例:奇數個套用到)
p:nth-child(2n+1){
color: blue;
font-size: 20px;
}
{% embed url="https://codepen.io/carlos411/pen/vYBJVRX" %}
元素有 focus 狀態的時候會套用到:
input:focus {
background-color: yellow;
}
{% embed url="https://codepen.io/carlos411/pen/MWgvPVz" %}
欄位被勾選的狀態時,會套用到
input:checked + label{
color: red;
}
{% embed url="https://codepen.io/carlos411/pen/xxKLyjx" %}
/* 只會套用到屬性有 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;
}
例:
{% embed url="https://codepen.io/carlos411/pen/RwbZeyK" %}