1.css3新增属性选择器
属性选择器可以根据元素特定属性来选择元素。这样可以不用借助类或者id选择器
注:类选择器,属性选择器,伪类选择器权重是10
例:
1.
元素[属性]
必须是input 但是同时具有value这个属性 选择这个元素
HTML
<input type="text" value="请输入用户名">
Css
input[value] {
color: pink;
}
元素[属性=“值”]
只选择type = text 文本框的input 选取出来
HTML
<input type="text" name="" id="">
Css
input[type=text] {
color: pink;
}
元素[属性^=“值”]
HTML
选择首先是div 然后 具有class属性 并且属性值 必须是icon开头的这些元素
<div class="icon1">小图标1</div>
<div class="icon2">小图标2</div>
Css
div[class^=icon] {
color: red;
}
元素[属性$=“值”]
属性选择器可以选择属性值结尾的某些元素
HTML
<section class="icon1-data">123</section>
<section class="icon2-data">abc</section>
Css
section[class$=data] {
color: skyblue;
}
元素[属性*=“值”]
只要类名值中包含某些元素,就可以使用属性选择器选择出
HTML
<span class="ico1">123</span>
<span class="ico2">456</span>
Css
span[class*=ico] {
color: greenyellow;
}
2.css3新增结构伪类选择器
结构伪类选择器主要根据文档结构来选择元素,常用于根据父级选择器里面的子元素
1.
父元素 子元素:first-child
匹配父元素中的第一个子元素
父元素 子元素:last-child
匹配父元素中最后一个子元素
父元素 子元素:nth-child(n)
匹配父元素中第n个子元素
HTML
<ul>
<li>我是第1个</li>
<li>我是第2个</li>
<li>我是第3个</li>
<li>我是第4个</li>
<li>我是第5个</li>
<li>我是第6个</li>
<li>我是第7个</li>
<li>我是第8个</li>
</ul>
Css
/选择ul里面的第一个/
ul li:first-child {
background-color: aquamarine;
}
/选择ul里面的最后一个/
ul li:last-child {
background-color: pink;
}
/选择ul里面的第三个/
ul li:nth-child(3) {
background-color: greenyellow;
}
父元素 子元素:nth-child(even)
把所有偶数的子元素选出来
父元素 子元素:nth-child(odd)
把所有奇数的子元素选出来
父元素 子元素:nth-child(n)
选择所有的子元素
HTML
<ul>
<li>我是第1个</li>
<li>我是第2个</li>
<li>我是第3个</li>
<li>我是第4个</li>
<li>我是第5个</li>
<li>我是第6个</li>
<li>我是第7个</li>
<li>我是第8个</li>
</ul>
Css
/ 1.把所有的偶数的子元素都选出来 /
ul li:nth-child(even) {
background-color: #ccc;
}
/2.把所有的奇数odd的子元素选出来 /
ul li:nth-child(odd) {
background-color: pink;
}
/3.nth-child(n) 这里面必须是n 不能是其他的字母 选择所有的子元素/
ul li:nth-child(n) {
background-color: pink;
}
/ 4.nth-chid(2n) 选择了所有偶数的子元素 等于even /
ul li:nth-child(2n) {
background-color: yellow;
}
/5./
ul li:nth-child(2n+1) {
background-color: blue;
}
父元素 子元素:first-of-type
父元素 子元素:last-of-type
父元素 子元素:nth-of-type(n)
使用方法与nth-child相似
区别:
1.nth-child 对父元素里面所有孩子排序选择,先找到第n个孩子,然后再看是否与子元素匹配
2. nth-of-type 对父元素里面指定的子元素进行排序选择。先匹配子元素,然后再根据子元素找第n个孩子
3.伪元素选择器before和after
::before 在元素内部的前面插入内容
::after 在元素内部的后面插入内容
注:
1.before和after创建一个元,是行内元素
2.创建的这个元素,文档树中找不到,所以称为伪元素
3.语法: 元素::before{}
3.before和after必须有content属性
4.伪元素选择器和标签选择器一样,权重为1
例:
HTML
<div>喜欢</div>
Css
div {
width: 200px;
height: 200px;
background-color: pink;
}
div::before {
/* 这个content是必须写的 */
content: '我';
display: inline-block;
width: 30px;
height: 40px;
background-color: skyblue;
}
div::after {
content: '你';
}
效果图: