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

 

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

1. 后代选择器

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

css:css

h1 em {color:red;}

 HTML: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>

运行结果: spa

  • h1 em的写法适用于h1中的的全部em,且无论em嵌套多少层都会适用
<h1>This is a <span><p><em>important</em></p></span> heading</h1>

 运行结果:code

2. 子选择器

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

第二个h1中,由于strong的父元素不是h1,而是em,因此css中的设置不会对它起做用blog

css:get

h1 > strong {color:red;}

HTML:it

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

 

运行结果: class

3. 相邻兄弟选择器

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

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>

 

运行结果: 

 

 例程来源:

相关文章
相关标签/搜索