偽類

元素狀態,使用 : 符號

游標停留 :hover

.block {
    width: 100px;
    height: 100px;
    background: #000;
    color: #fff;
    margin: 10px auto;
    display: flex;
    justify-content: center;
    align-items: center;
}

.block:hover {
    background: red;
}

demo

已選取 :checked

用於可切換選取狀態的元素

  • radio
  • checkbox
.on-checked:checked {
    width: 100px;
    height: 100px;
}

demo

反向 :not(selector)

.block {
    background: red;
}

.block div:not(.item) {
    color: yellow;
}

demo

子層指定 :nth-child(n)

ul li:nth-child(3) {
    background: red;
    color: yellow;
}

demo

子層倍數指定 :nth-child(an+b)

a 基數

n0 開始自動遞增

b 常數

ul.n2 li:nth-child(2n) {
    background: red;
    color: yellow;
}

ul.n2_1 li:nth-child(2n + 1) {
    background: red;
    color: yellow;
}

ul.n3 li:nth-child(3n) {
    background: red;
    color: yellow;
}

demo

子層第一個 :first-child

等同 :nth-child(1)

ul li:first-child {
    background: red;
    color: yellow;
}

demo

子層最後一個 :last-child

ul li:last-child {
    background: red;
    color: yellow;
}

demo