后代选择器
css的后代选择器h1 strong {color:red;}
这一语句会使所有h1中的strong块中元素起作用,
如图所示:
<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>
结果为:
子元素选择器
而将css样式改为h1>strong {color:red
则只对h1的直接下属标签strong中的元素起作用,如果h1与strong之间还插有隔有一个标签,则不会显示.
<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>
兄弟选择器
<head>
<style type="text/css">
li + li {font-weight:bold;}
</style>
</head>
<body>
<div>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>list item 4</li>
</ul>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
</div>
</body>
结果:
而如果多加一个li:
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
li + li+li {font-weight:bold;}
</style>
</head>
<body>
<div>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
</div>
</body>
</html>
结果是这样:
很迷,不知道该如何总结.
刚找了资料,发现原来是这样的:
选择器样式:li+li{}时,字面意思是选取所有位于
<li>
标签后的第一个<li>
元素,
(1) 很显然第一个<li>
标签不会选中,因为它前面不是<li>
;
(2) 第二个<li>
标签会选中,因为它是第一个<li>
标签紧邻的<li>
标签;
(3) 第三个<li>
标签也会选中:因为第三个<li>
标签的上一个标签也是<li>
标签,也满足css选择器li+li{}的条件:<li>
标签后的第一个<li>
元素
.
正因为css选择器的样式为li+li{},所以代码中的li标签就可以一直套用这个“公式”。是引用.
看下面代码:
<html>
<head>
<style type="text/css">
h3 + p {color:red;}
</style>
</head>
<body>
<h3>第一个标题3.</h3>
<h4>this is a 标题4.</h4>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<h3>第2个标题3</h3>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<h3>第3个标题3</h3>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
</body>
</html>
结果如图:
上面的代码中所用选择器为h3+p{},我们可以看到,第一个h3和p之间因为有一个h4,所以并不符合条件,而之后有两个符合条件的h3+p组合,则两个p标签全部都飘红,说明在数量上并没有限制,只要符合要求就可以.
还有三者混合搭配的
说实话,第一眼看到这条语句真的把我给看晕了
html > body table + ul {margin-top:20px;}
这个是w3school上关于css的教程中的例子,作为新手的我就是在这个网站上面学习的基础知识
言归正传,还是按照官方教程中对这三种选择器的读法来,即从右到左读:
选择紧接在 table 元素后出现的所有兄弟 ul 元素,该 table 元素包含在一个 body 元素中,body 元素本身是 html 元素的子元素。
新手第一次发博客,若有错误的地方,还望大家不吝赐教,多多指出来.