由于css中的类选择器用法较多,时间长了,总是容易遗忘,因此对这部分内容做了一些简单的总结
一、后代选择器
<html>
<head>
<style type="text/css">
ul em {color:red; font-weight:bold;}
</style>
</head>
<body>
<ul>
<li>List item 1
<ol>
<li>List item 1-1</li>
<li>List item 1-2</li>
<li>List item 1-3
<ol>
<li>List item 1-3-1</li>
<li>List item <em>1-3-2</em></li>
<li>List item 1-3-3</li>
</ol>
</li>
</ol>
</li>
</ul>
</body>
</html>
后代选择器中的后代可以是多层次的深层嵌套,选择器之间用空格连接
二、子元素选择器
<html>
<head>
<style type="text/css">
h1 > strong {color:red;}
</style>
</head>
<body>
<h1>This is <strong>very</strong> <strong>very</strong> important.</h1>
<h1>This is <em>really <strong>very</strong></em> important.</h1>
</body>
</html>
相比于后代选择器,子元素选择器只能选择父元素中的一代子元素,选择器之间用>连接,可以存在空格
三、相邻兄弟选择器
<html>
<head>
<style type="text/css">
p + li {font-weight:bold;}
</style>
</head>
<body>
<div>
<ul>
<p>List item 1</p>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
</body>
</html>
选择紧接在另一个元素后的元素,而且二者有相同的父元素,此时可以使用相邻兄弟选择器。选择器之间用+连接,可以存在空格
四、选择器分组
<html>
<head>
<style type="text/css">
h1, h2, h3, h4, h5, h6 {color:blue;}
</style>
</head>
<body>
<h1>这是 heading 1</h1>
<h2>这是 heading 2</h2>
<h3>这是 heading 3</h3>
</body>
</html>
选择器之间用逗号隔开,可以没有空格,并不影响
五、类选择器
<html>
<head>
<style type="text/css">
p.important {color:red;}
h1.important {color:blue;}
</style>
</head>
<body>
<h1 class="important">This heading is very important.</h1>
<p class="important">This paragraph is very important.</p>
<p>This is a paragraph.</p>
</body>
</html>
类选择器可以结合元素选择器一起使用,二者之间不能存在空格,否则会变成后代选择
六、属性选择器
<html>
<head>
<style type="text/css">
[title]
{
color:red;
}
</style>
</head>
<body>
<h2 title="Hello world">Hello world</h2>
<hr />
<h2>Hello world</h2>
</body>
</html>
属性选择器可以根据元素的属性及属性值来选择元素,该选择器还可以搭配子串匹配进行使用