前言
纯记录贴。今天突然看到的文章。记录一下,以防忘掉。不喜轻喷。
元素或组选择器
常用方法:
//元素选择器
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;
}