子选择器和后代选择器

子选择器

子选择器选择作为指定元素的子元素的所有元素。

以下示例选择作为 <div> 元素的子元素的所有 <p> 元素:

<!DOCTYPE html>
<html>
<head>
<style>
div p {
background-color: yellow;
}
</style>
</head>
<body>

<h2>Child Selector</h2>

<p>The child selector (>) selects all elements that are the children of a specified element.</p>

<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<section><p>Paragraph 3 in the div.</p></section> /* 所以这一行不是黄色的*/
</div>

<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>

</body>
</html>

 后代选择器

 

后代选择器匹配作为指定元素的后代的所有元素。

 

以下示例选择 <div> 元素内的所有 <p> 元素: 

 

 

<!DOCTYPE html>
<html>
<head>
<style>
div>p {
background-color: yellow;
}
</style>
</head>
<body>

 

<h2>Descendant Selector</h2>

 

<p>The descendant selector matches all elements that are descendants of a specified element.</p>

 

<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<section><p>Paragraph 3 in the div.</p></section> /* 所以这一行是黄色的*/
</div>

 

<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>

 

</body>
</html>

 

posted @ 2022-02-22 09:45  我的猫在哪里  阅读(317)  评论(0)    收藏  举报