类选择器
又名“标签名选择器”或者是”元素选择器“,因为它在文档中选择的对象是一个HTML标签/元素。
先定义类,才有选择类。
元素内添加
语法:
.类名{
声明
}
id选择器
元素内添加上
id="id名"
<style>
/* 用法一: */
#one{
background-color: green;
}
<h2 id="one">我是id选择器一</h2>
通配符选择器
在CSS中,通配符选择器使用 * 定义,表示选取页面中所有元素(标签)。
*{
声明
}
包含选择器
子代选择器 选中亲生儿子(>)
后代选择器 找到后代所有要找的元素
<style>
/* 子代选择器 选中亲生儿子*/
.a>li {
background-color: pink;
}
/* 后代选择器 找到后代所有要找的元素*/
.a li {
color: blueviolet;
}
</style>
</head>
<body>
<ul class="a">
<li>1</li>
<li>1</li>
<li>1</li>
<li>1</li>
<ul>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</ul>
复合选择器
同时声明多个
div,
p,
span {
color: red;
}
属性选择器
属性选择器用来选中带有特定属性的元素。
属性选择器是基于一个元素自身是否存在(例如href)或者基于各式不同的按属性值的匹配,来选取元素。input[type=" "]{ }
input[type="password"] {
background-color: aquamarine;
}
div[id] {
width: 300px;
height: 300px;
background-color: blue;
}
/* type^="te"以te开头 */
input[type^="te"] {
background-color: red;
}
input[type$="l"] {
background-color: green;
}
/* type*="e" type值里边包含e */
input[type*="e"] {
background-color: chartreuse;
}
</style>
</head>
<body>
<input type="text"><br />
<input type="password"><br />
<input type="search"><br />
<input type="url"><br />
<input type="number"><br />
<div id="aquamarine">1</div>
<div>2</div>
伪类选择器
1.伪类选择器用于向某些选择器添加特殊的效果,比如给链接添加特殊效果,或选择第一个,第n个元素。
2.伪类选择器使用冒号(:)表示,比如:hover。
3.伪类选择器很多,比如链接伪类、结构伪类等。
伪类选择器:
1)E:link
2)E:visited
3)E:hover
4)E:active
5)E:not(S) 匹配不包含S的E元素
6)E:first-child
7)E:last-child
8)E:only-child
9)E:empty
10)E:checked
11)E:nth-child(n)
/* :hover 鼠标悬停 */
/* cursor 鼠标样式 */
4.链接伪类选择器:
包含的情况
例子:
.three img {
display: none;
position: absolute;
bottom: -130px;
left: 0;
.three:hover img {
display: block;
<a href="#" class="three">
五彩导航
<img src="../code.jpg" alt="">
</a>
结构伪类选择器
结构伪类选择器的作用:
根据元素在HTML中的结构关系查找元素结构伪类选择器的优势
减少对于HTML中类的依赖,有利于保持代码整洁结构伪类选择器的用途
常用于查找某父级选择器中的子元素
E:first-child 选择父元素的第一个子元素 E:last-child 选择父元素的最后一个子元素 E:nth-child(n) 选择父元素下的第 n 个子元素 E:nth-last-child(n) 选择父元素中倒数第n个子元素
nth-child():nth-child → 直接在所有孩子中数个数
功能 公式 偶数 2n、even 奇数 2n+1、2n-1、odd 找到前5个 -n+5 找到从第5个往后 n+5 n为:0、1、2、3、4、5、6、…
nth-of-type → 先通过该 类型 找到符合的一堆子元素,然后在这一堆子元素中数个数
E:nth-of-type(n) {} 只有父元素的同类型( E)子元素范围中,选择第n个
伪元素选择器
伪对象即伪元素,表示DOM外部的某种文档结构。
伪元素改变文档结构,在结构外另加一个没有实际存在的元素(即伪元素)。
常用伪元素:
1)E:before/E::before
2)E:after/E::after
/* input::placeholder 表单提示词 */
例子
input::placeholder {
color: rgb(62, 226, 56);
}
/* ::selection 选中时 */
例子
ul li:nth-child(4)::selection {
color: pink;
}