选择器
- 选择页面上的元素
2.1 基本选择器
标签选择器
会选择页面上所有的这类标签的元素
h1{
color:red;
}
p{
color:black;
}
类选择器
- .+class名称
- 可以用class为不同的标签归类,同一个class效果一样,方便复用
h1 和 p都变红
<style>
.new{
color:red;
}
</style>
<h1class = "new">1111</h1>
<pclass = "new">
222
</p>
Id选择器
# + id名称{}
- id必须保证全局唯一
<style>
#name{
color : red;
}
</style>
<h1id = "name"></h1>
优先级
id > class >标签
层次选择器
后代选择器
- 某个元素的后面的所有对应元素
body p{
color :red;
}选中body中所有的p
子选择器
- 只有一代,儿子
body>p{
background: red;
}
相邻兄弟选择器
- +只有一个,相邻同级元素(向下)
.active + p{
background:red;
}
通用选择器
- ~ 当前选中元素的向下的所有兄弟(同级)元素
<style>
.active~p{
background:red;
}
</style>
<p>dsds</p>
结构伪类选择器
- 伪类选择器:
<head>
<style>
/*ul的第一个子元素*/
ulli:first-child{
background:black;
}
/*ul的最后一个子元素*/
ulli:last-child{
background:red;
}
/*
选中p1
选中当前p元素的父级元素,再选中父级元素的第一个元素(必须是对应的p元素,否则不生效)
按顺序选择
*/
p:nth-child(1){
background:red;
}
/*
选中父元素下的第二个p元素
按照类型选择
*/
p:nth-of-type(2){
background:blue;
}
</style>
</head>
<body>
<p>p1</p>
<p>p2</p>
<p>p3</p>
<ul>
<li>li1</li>
<li>li2</li>
<li>li3</li>
</ul>
</body>
属性选择器(常用)
属性名,属性名 = 属性值(正则)
= 绝对等于
相当于类选择器和id选择器结合
*= 包含这个元素
^= 以这个开头
$= 以这个结尾
a[id]{ 选中a标签中存在id属性的元素
color:red;
}
a[id=first]{
color:red;
}
a[class*="links"]{
}
a[href^=http]{
}
<aid = first></a>