本页主要展示一些不常见的选择器用法,包括:伪类、伪元素、选择器组合

一、伪类

「伪类」,以冒号:开头,用于选择处于特定状态的元素

(1)动态伪类

#btn-1:hover {
    transform: scale(1.2);
}
#input-1:focus {
    background-color: antiquewhite;
}

(2)结构伪类

第1行
第2行
第3行
第4行
第5行
第6行
.nth指容器,div指每一行,div:nth-child(even)指所有偶数元素
.nth div:nth-child(even) {
    color: red;
}

二、伪元素

「伪元素」,以双冒号::开头,用于在文档中插入虚构的元素

Hello world
#context-1::first-letter {
    font-size: 1.5rem;
}
出错了!
.error {
    position: relative;
    display: inline-block;
    padding: 12px 30px;
    /* 设置一个左padding,是为了放下before内的元素 */
}

.error::before {
    /* content必须设置,即使为空 */
    content: '';
    background-image: url(../asset/error.svg);
    background-size: 15px;
    display: inline-block;
    width: 15px;
    height: 15px;
    /* 相对定位,修正before元素的位置 */
    position: absolute;
    left: 10px;
    top: 15px;
}