css的十种选择器记录

前言

纯记录贴。今天突然看到的文章。记录一下,以防忘掉。不喜轻喷。

元素或组选择器

常用方法:

//元素选择器
p {
	color:red;
}
//组选择器
p , h2{
	color:red;
}

ID选择器

常用方法:

#box{
    color: red;
}

id不能重名,否者使用id对js语法不太友好。如果需要多个相同名称,建议使用class

class选择器

常用方法:

.box {
	color: red;
}

最常用的选择器,优点看id选择器。

属性选择器

常用选择器。多用于给指定的某一些元素加样式。常用方法:

//需在html标签中添加rel标记
div[rel='div-rel'] {
	color: red;
}
//标记所有类型为复选框的input
input[type='checkbox'] {
	color: red;
}

后代选择器

常用方法:

div p{
	color: red;
}
ui li p{
	color: red;
}
.box p{
	color: red;
}

子选择器

常用方法:

div > p {
	color: red;
}

与后代选择器不同的是,子选择器只会对子级起效。对孙级或更下级无效。

相邻和通用同级选择器

常用方法:

//只有直接与div相邻的p元素才会受到影响
div + p {
	color: red;
}
//所有与div同级的p元素都会受到影响
div ~ p {
	color: red;
}

星号选择器*

常用方法

//所有元素都会受到影响
* {
	color: red;
}
//所有div元素都会受到影响
div * {
	color: red;
}

不建议过多的使用*选择器。会给浏览器带来不必要的负担。

伪类选择器

常用方法:

//常用来处理样式变化后或特殊场景下的样式。
.box::before {
	content:'';
}
//当鼠标移动至按钮上时,改变颜色。
button:hover {
	color: red;
}

nth-type/nth-child

常用方法:

//第二个P标签将会受到影响
p:nth-of-type(2) {
	color: red;
}
//所有将P元素为父元素的子元素中,第二个将受到影响。
p:nth-child(2) {
	color: red;
}
div:nth-of-type(2) p:nth-child(2){
	color: red;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值