一、css的继承
-在style中设定div的颜色为红色,<p>、<h1>、<h2>不设置任何样式
<style type="text/css">
div{
color: red;
}
</style>
<body>
<div>
我是第一层div
<p>我是段落
<h1>我是一级标题
<h2>我是二级标题</h2>
</h1>
</p>
</div>
</body>
-结果<p>、<h1>、<h2>继承了div的样式,颜色都变成红色
-最为常见的可继承属性有 color、font-size、font-style等非常多的属性
-注意并非所有属性都可继承
二、后代选择器
-写一段 style 样式,设置ul的em元素为红色
<style type="text/css">
ul em{
color:red;
}
</style>
<body>
<ul>
<li><em>被选择了</em>
<ol>
<li><em>被选择了</em>
<ol>
<li>
<em>被选择了</em>
</li>
</ol>
</li>
</li>
</ol>
</li>
</ul>
</body>
-ul和ol的区别在其符号的不同,可通过type属性更改符号
-ul元素与后代元素em之间的层次间隔可以无限
-任意后代em元素都被设为红色
三、子选择器【>】
-style样式设置子元素的颜色为绿色,字体大小为20像素
<style type="text/css">
h1>em{
color: green;
font-size:20px;
}
</style>
<body>
<h1>
<em>我是第一个em</em>
<p><em>我是第二个em</em></p>
<h2><em>我是第三个em</em></h2>
</h1>
</body>
-观察效果图,第一个子元素em被选中,第二第三个em元素都没有选中
-父元素与子元素之间有层次间隔会破坏子选择器的作用效果
四、相邻选择器【+】
-相邻选择器语法规则:相邻兄弟选择器使用了加号(+)
<style type="text/css">
li+li{
font-weight:bold;
}
</style>
<body>
<div>
<ul>
<li>List item1</li>
<li>List item2</li>
<li>List item3</li>
</ul>
<ol>
<li>List item1</li>
<li>List item2</li>
<li>List item3</li>
</ol>
</div>
-效果图如下:item1的兄弟是item2,item2的兄弟是iem3,item2与item3都被选中
-再看看w3School上的demo,以下内容出自W3School
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
h1 + p {color:red}
</style>
</head>
<body>
<h1>This is a heading.</h1>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
</body>
</html>
-效果图:h1的兄弟是第一个<p>被选中,字体变为红色
相邻兄弟结合符还可以结合其他结合符:
html > body table + ul {margin-top:20px;}
这个选择器解释为:选择紧接在 table 元素后出现的所有兄弟 ul 元素,该 table 元素包含在一个 body 元素中,body 元素本身是 html 元素的子元素。