CSS伪类、伪元素

CSS伪类、伪元素

一、伪类

:hover

鼠标🖱悬停时的伪类,如:

/*	鼠标悬停到.box上时背景颜色变为红色	*/
.box:hover {
	background-color: red;
}

:active

鼠标🖱点击时的伪类,如:

/*	鼠标点击时背景颜色变为灰色	*/
.box:active {
    background-color: grey;
}

:not()

不选择指定的选择器,如:

/*	选中所有用了.box类选择器且不是h1标签的元素	*/
.box:not(h1) {
	font-size: 16px;
}

:focus

输入表单得焦点时的伪类,如:

/*	input获得焦点后背景变为粉红色	*/
input:focus {
    background-color: pink;
}

:first-child

父容器中第一个元素,且这个元素类型必须指定类型一致,有点不好直接理解,没关系,看代码:happy:

/*	.box的第一个孩子,且必须是p标签,才选中	*/
.box p:first-child {
    color: red;
}

:last-child

父容器中最后一个元素,且这个元素类型必须指定类型一致

/*	.box的最后一个孩子,且必须是p标签,才选中	*/
.box p:last-child {
    color: red;
}

:nth-child()

父容器中指定序号的元素(序号从1开始),且这个元素类型必须指定类型一致

/*	.box的第二个子元素,且必须是div类型	*/
.box div:nth-child(2) {
    width: 200px;
}
/*	n范围为[0,+oo),所以 2n + 1 范围 [1, +oo),即选中.box中序号为1,3,5,...等元素,且必须是div类型	*/
.box div:nth-child(2n + 1) {
    width: 200px;
}

:nth-last-child

从父容器中倒着取指定序号的元素,且这个元素类型必须指定类型一致

/*	.box的倒数第二个子元素,且必须是div类型	*/
.box div:nth-last-child(2) {
    width: 200px;
}
/*	选中.box1中倒数第一个,倒数第三个,...等元素,且必须是div类型	*/
.box div:nth-last-child(2n + 1) {
    width: 200px;
}

:first-of-type

父容器中第一个指定类型的元素,如:

/*	选中.box中第一个div,将高度设为100px	*/
.box div:first-of-type {
    height: 100px;
}

:last-of-type

父容器中最后一个指定类型的元素,如:

/*	选中.box中最后一个div,将高度设为100px	*/
.box div:last-of-type {
    height: 100px;
}

:nth-of-type

父容器中指定类型的元素第几个,如:

/*	选中.box中第二个div	*/
.box div:nth-of-type(2) {
    height: 100px;
}

/*	选中.box中第1, 3, 5, ...个div	*/
.box div:nth-of-type(2n + 1) {
    height: 100px;
}

:nth-last-type-of

与:nth-of-type取值顺序相反

:checked

勾选状态的表单,如:

<body>
	<input type="radio" chekced/>
	<input type="checkbox" checked/>
</body>
<style>
    input:checked {
        width: 30px;
        height: 30px;
    }
</style>

:disabled

选择禁用状态的表单,如:

<body>
	<input type="radio" disabled/>
	<input type="checkbox" disabled/>
</body>
<style>
    input:disabled {
        width: 30px;
        height: 30px;
    }
</style>

:enabled

选择可用状态的表单,如:

<body>
	<input type="radio"/>
	<input type="checkbox"/>
</body>
<style>
    input:enabled {
        width: 30px;
        height: 30px;
    }
</style>

二、伪元素

::before

在元素内容前插入一个虚拟元素

::after

在元素内容后插入一个虚拟元素

::selection

用户选中的文本

::placeholder

表单元素的占位符文本

以上伪元素使用方式如下:

<body>
	<h1>
        请输入你的名字
    </h1>
    <input type="text"/>
</body>
<style>
    /*	h1前添加[	*/
    h1::before {
        content: '['
    }
    /*	h1后添加]	*/
    h1::after {
        content: ']'
    }
    /*	h1中文本选中时改为红色	*/
    h1::selection {
        color: red;
    }
    /*	input占位字符颜色设置为灰色	*/
    input::placeholder {
        color: grey;
    }
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值