CSS系列之后代选择器、子选择器和相邻兄弟选择器

  • 后代选择器比子选择器的范围大,包含子选择器,且包含子选择器的“子孙”选择器,后代选择器使用"空格"符号间隔选择器
  • 子选择器:子选择器只是父选择器的一级子元素,使用">"符号链接选择器
  • 相邻兄弟选择器,是拥有相同父元素,且两个元素相邻,使用"+"符号链接

1. 后代选择器

  • 比如如下html代码,em是h1的后代元素,如下css样式这样写,只会影响h1中的em标签的内容变为红色,不会影响p中em的内容

css:

h1 em {color:red;}

 HTML:

<html>
<head>
<style type="text/css">
h1 em {color:red;}
</style>
</head>
<body>
<h1>This is a <em>important</em> heading</h1>
<p>This is a <em>important</em> paragraph.</p>
</body>
</html>

运行结果: 

  • h1 em的写法适用于h1中的的所有em,且不管em嵌套多少层都会适用
<h1>This is a <span><p><em>important</em></p></span> heading</h1>

 运行结果:

2. 子选择器

下面设置h1的子元素strong标签的内容为红色

第二个h1中,因为strong的父元素不是h1,而是em,所以css中的设置不会对它起作用

css:

h1 > strong {color:red;}

HTML:

<!DOCTYPE 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>

运行结果: 

3. 相邻兄弟选择器

h1和p拥有相同的父元素body,相邻兄弟选择器需要紧挨着,只会适用于与h1相邻的p标签的内容

css:

h1 + p {margin-top:50px;}

HTML:

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
h1 + p {margin-top:50px;}
</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只会对第一个p作用,再如下面的例子:

只会对两个列表的第二个及后面的li起作用,对第一个li不会起作用

css:

li + li {font-weight:bold;}

HTML:

<!DOCTYPE HTML>
<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>
  </ul>
  <ol>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
  </ol>
</div>
</body>
</html>

运行结果: 

 例程来源:

原文地址:https://www.cnblogs.com/china-fanny/p/11152986.html