2 选择器
作用:选择页面上的某一个或者某一类元素
2.1 基本选择器
- 标签选择器:选择一类标签 标签{}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*标签选择器,会选择到页面上所有的这个标签的元素*/
h1{
color: red;
background: aliceblue;
border-radius: 24px;
}
p{
font-size: 20px;
}
</style>
</head>
<body>
<h1>学java</h1>
<p>汤凯磊学</p>
<h1>标题二</h1>
</body>
</html>
- 类选择器 class :选择所有class属性一致的标签, 跨标签 .类名{}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*
类选择器的格式 .class的名称{}
好处,可以多个标签归类,跨标题
*/
.tkl{
color:red;
}
.zyj{
color:gainsboro;
}
</style>
</head>
<body>
<h1 class="tkl">biaoti1</h1>
<h1 class="zyj">biaoti2</h1>
<h1 class="tkl">biaoti3</h1>
<p class="zyj">zheship</p>
</body>
</html>
- Id选择器:全局唯一! #id名{}
优先级:id>class>标签
2.2 层次选择器
1、后代选择器:在某个元素的后面全变
body p{
background: red;
}
2、子选择器 一代 儿子
body>p{
background: green;
}
3、相邻兄弟选择器 只有下面一个同辈
.active + p{
background: purple;
}
4、通用选择器 当前选中元素的向下的所有兄弟元素
.active~p{
background: aqua;
}
2.3 结构伪类选择器
伪类:
/* ul的第一个子元素*/
ul li:first-child{
background: antiquewhite;
}
/*定位到父元素,选择当前的第一个元素,并且是当前元素才生效*/
p:nth-child(2){
background: blue;
}
/*定位到父元素,选中父元素下的p元素的第二个*/
p:nth-of-type(3){
background:brown;
}
动作:选中后背景变色
a:hover{
background: yellow;
}
2.4 属性选择器
<style>
.demo a{
float: left;
display: block;
height: 50px;
width: 50px;
border-radius: 10px;
background: yellow;
text-align: center;
color: brown;
text-decoration: none;
margin-right: 5px;
font:bold 20px/50px Arial;
}
/*!* 存在id属性的元素,属性名,属性名=属性值*!*/
/* =是绝对等于 *=是包含这个 ^= 以这个开头 $= 以这个结尾*/
/* a[id]{*/
/* background: blue;*/
/* }*/
/* a[id*=first]{*/
/* background: antiquewhite;*/
/* }*/
/* 选中class中links的元素*/
a[class*=links]{
background:saddlebrown;
}
</style>
<body>
<p class="demo">
<a href="http://www.baidu.com" class="links item first" id="first">1</a>
<a href="http://www.google.com" class="links item" title="test">2</a>
<a href="images/123.html" class="item" id="second">3</a>
<a href="images/123.png" class="item" id="third">4</a>
<a href="/a.pdf" class="links item" id="forth">5</a>
</p>
属性选择器更常用