层次选择器
选择器 | 类型 | 功能描述 |
---|---|---|
E F | 后代选择器 | 选择匹配的F元素,且匹配的F元素被包含在匹配的E元素内 |
E>F | 子选择器 | 选择匹配的F元素,且匹配的F元素是匹配的E元素的子元素 |
E+F | 相邻兄弟选择器 | 选择匹配的F元素,且匹配的F元素紧位于匹配的E元素后面 |
E~F | 通用兄弟选择器 | 选择匹配的F元素,且位于匹配的E元素后的所有所有匹配的F元素 |
后代选择器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
body p{ <!--对body标签下的所有p标签生效 -->
background-color:red;
}
</style>
</head>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<ul>
<li><p>4</p></li>
<li><p>5</p></li>
<li><p>6</p></li>
<ul>
</body>
</html>
效果图
子选择器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
body>p{ <!--只对子标签p生效 -->
background-color:red;
}
</style>
</head>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<ul>
<li><p>4</p></li>
<li><p>5</p></li>
<li><p>6</p></li>
<ul>
</body>
</html>
效果图
相邻兄弟选择器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.p1+p{ <!-- 只对和p1相邻的p标签生效(不包括p1)-->
background-color:red;
}
</style>
</head>
<body>
<p class="p1">1</p>
<p>2</p>
<p>3</p>
<ul>
<li><p>4</p></li>
<li><p>5</p></li>
<li><p>6</p></li>
<ul>
</body>
</html>
效果图
通用兄弟选择器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.p1~p{ <!--对p1后面的所有兄弟p标签生效(不包括p1)-->
background-color:red;
}
</style>
</head>
<body>
<p class="p1">1</p>
<p>2</p>
<p>3</p>
<ul>
<li><p>4</p></li>
<li><p>5</p></li>
<li><p>6</p></li>
<ul>
</body>
</html>
效果图
结构伪类选择器
选择器 | 功能描述 |
---|---|
E:first-child | 作为父元素的第一个子元素的元素E |
E:last-child | 作为父元素最后一个子元素的元素E |
E F:nth-child(n) | 选择父级元素E的第n个子元素F,(n可以是1,2,3) |
E:first-of-type | 选择父元素内具有指定类型的第一个E元素 |
E:last-of-type | 选择父元素内具有指定类型的最后一个E元素 |
E F:nth-of-type(n) | 选择父元素E内具有指定类型的第n个F元素 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
ul li:first-child{ <!--ul标签的第一个元素li -->
background:red;
}
ul li:last-child{ <!--ul标签的最后一个元素li -->
background:green;
}
p:nth-child(1){ <!--父级里第一个子元素p-->
background:yellow;
}
p:nth-of-type(2){ <!--父级里第2个p元素-->
background:blue;
}
</style>
</head>
<body>
<p class="p1">1</p>
<p>2</p>
<p>3</p>
<ul>
<li>li1</li>
<li>li2</li>
<li>li3</li>
</ul>
</body>
</html>
效果图
属性选择器
属性选择器 | 功能描述 |
---|---|
E[attr] | 选择匹配具有属性attr的E元素 |
E[attr=val] | |
E[attr^=val] | 选择匹配元素E,且E元素定义了属性attr,其属性值是以val开头的任意字符串 |
E[attr$=val] | 选择匹配元素E,且E元素定义了属性attr,其属性值是以val结尾的任意字符串 |
E[attr*=val] | 选择匹配元素E,且E元素定义了属性attr,其属性值包含了val |