属性选择器
以下 E 代表标签名, attr 表示属性名 ,val 表示属性值
1. E[attr] 选择所有 具有 attr属性的 E 元素
2. E[attr=val] 选择所有 具有 attr属性并且他的值是val的 E元素
3. E[attr~=val] 选择所有 具有 attr属性并且他的值 包含 val 的E元素
4. E[attr|=val] 选择所有 具有 attr属性并且他的值是以val 或者 val- 开头的 E元素
5. E[attr*=val] 选择所有 具有 attr属性并且他的值具有 val 字符的E元素
6. E[attr$=val] 选择所有 具有 attr属性并且他的值是以 val 字符结束的E元素
7. E[attr^=val] 选择所有 具有 attr属性并且他的值是以 val 字符开始的E元素
/* 属性class的值是abc */
li[class="abc"]{
border: #f00 1px solid;
}
/* 属性class中包含 show */
li[class~="show"]{
width: 200px;
height: 200px;
background: #04be02;
}
/* 属性class中的 字符以abc开头或者abc-开头 */
div[class|="abc"]{
font-size: 30px;
color: #f00;
}
/* 属性class中的 字符含有bc开 */
div[class*="bc"]{
border: #f00 1px solid;
margin: 10px 0;
}
/* 属性class 的值以 li 开头*/
div[class^='li']{
color: #04be02;
}
/* 属性class 的值以 d 结尾*/
div[class$='d']{
color: #00f;
}
/* 给所有的文本输入框设置样式 */
input[style="text"]{
color: #04be02;
}
伪类选择器
:focus 为所有获取焦点的input设置样式
:disabled 为所有被禁用的input设置样式
:target 目标伪类选择器,当跳转到他所修饰的元素上的时候才会执行该选择器修饰的样式
:root 表示的是 html
E:empty 选中所有内容为空的E标签,并添加样式
:empty 选中所有内容为空的标签,并添加样式
E:only-child 选中父元素中只有一个E标签的 E标签,并添加样式,独生子标签
input[type="text"]:focus{
position: relative;
width: 200px;
height: 30px;
padding-left: 10px;
}
input:disabled{
border: 1px #f00 solid;
}
:target{
color: #f00;
}
:root{
border: 2px #00f solid;
}
div:empty{
border: 1px #f00 solid;
width: 100px;
height: 100px;
}
:empty{
background: #ccc;
}
div:only-child{
font-size: 30px;
}
伪元素选择器
伪元素选择器:通过伪元素选择器可以给元素添加一个类似子元素的内容,不是真正的标签
使用伪元素需要添加::
::first-letter 表示修饰第一个字符
::first-line 表示修饰第一行字符
::before 在元素内容的最前面添加一个伪元素
::after 在元素内容的最后面添加一个伪元素
.txt::first-letter{
font-size: 30px;
color: #04be02;
}
.txt::first-line{
font-size: 20px;
color: #f00;
}
.cont::before{
content: '张杰';
border: 1px #f00 solid;
font-size: 30px;
color: #04be02;
display: block;
}
.cont::after{
content: '谢娜';
border: 1px #f00 solid;
font-size: 30px;
color: #04be02;
}
结构伪类选择器
父级 E:nth-child(number) 选中同一个父级下,排名次序伪 num的E元素
num 从1开始
使用n表达式,设置选中的标签,n从0开始计算
偶数使用 2n
奇数使用 2n+1
E:nth-child(2n)
E:nth-child(2n+1)
也可以使用 odd 表示奇数,even表示偶数
E:nth-last-child(num)表示从后开始往前数,使用方式和 nth-child 一样,也就是倒着计算
ul>li:nth-child(2){
background: #f60;
}
ul li:nth-child(6){
background: #f6f;
}
ul li:nth-child(10){
background: #f60;
margin-bottom: 0;
}
/* 偶数 */
ul li:nth-child(2n){
background: #ff0;
margin-bottom: 0;
}
/* 奇数 */
ul li:nth-child(odd){
background: rgb(98, 0, 255);
margin-bottom: 0;
height: 60px;
}
ul li:nth-last-child(2){
font-size: 30px;
}
如果父元素中的子元素不是同一个类型,则不能使用 nth-child(num)来设置css,以为匹配到的元素不对
使用 nth-of-type(num)来匹配元素,他的意思是,找到和E标签同类型的第num个元素
nth-last-of-type(num) 使用方法和 nth-of-type(num) 一样,只是倒着数
.cont p:nth-of-type(2){
font-size: 30px;
color: #f00;
}
.cont span:nth-of-type(2){
font-size: 30px;
color: #f0f;
}
.cont span:nth-last-of-type(1){
font-size: 30px;
color: #f0f;
}