介绍几个工作中比较实用的css选择器
示例html结构
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="static/css/index.css"/>
</head>
<body>
<div class="list">
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
<p>p5</p>
<p>p6</p>
<p>p7</p>
<p>p8</p>
<p>p9</p>
<p>p10</p>
</div>
</body>
</html>
基础部分css
*{
margin: 0;
padding: 0;
}
.list{
width: 500px;
margin: 0 auto;
}
.list p{
line-height: 30px;
height: 30px;
margin-bottom: 10px;
background: orange;
color: #ffffff;
text-align: center;
}
:first-child
选择同级元素下的第一个元素
.list p:first-child{
background: red;
}
:last-child
选择同级元素下的最后一个元素
.list p:last-child{
background: red;
}
:nth-child(n)
选择同辈元素中的第几个
例如:改变list下第三个p标签的背景色
.list p:nth-child(3){
background: red;
}
倍数写法 :nth-child(an) //a为数字
例如 选择2的倍数元素
.list p:nth-child(2n){
background: red;
}
奇偶匹配 :nth-child(odd) :nth-child(even)
/* 匹配奇数子元素p */
.list p:nth-child(odd){
background: blue;
}
/* 匹配偶数子元素p */
.list p:nth-child(even){
background: darkgoldenrod;
}
:not()
匹配不包含括号内的规则的元素
例如:匹配不包含class为 item的元素
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="static/css/base.css">
<link rel="stylesheet" type="text/css" href="static/css/index.css"/>
</head>
<body>
<div class="list">
<p>p1</p>
<p class="item">p2</p>
<p class="item">p3</p>
<p class="item">p4</p>
<p>p5</p>
<p>p6</p>
<p>p7</p>
<p>p8</p>
<p>p9</p>
<p>p10</p>
</div>
</body>
</html>
css
.list p:not(.item){
background: blue;
}
:empty
匹配不包含任何内容以及元素的节点
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="static/css/base.css">
<link rel="stylesheet" type="text/css" href="static/css/index.css"/>
</head>
<body>
<div class="list">
<p>p1</p>
<p class="item">p2</p>
<p class="item">p3</p>
<p class="item">p4</p>
<!-- 几个空的p标签 -->
<p></p>
<p></p>
<p></p>
<p>p8</p>
<p>p9</p>
<p>p10</p>
</div>
</body>
</html>
css
.list p:empty{
background: blue;
}