CSS - 子选择器
CSS 中的子选择器
CSS 子选择器用于选择特定元素的直接子元素。通过 >(大于)符号表示。它不会选择嵌套在子元素内部的更深层元素。
语法
CSS 子选择器的语法如下:
selector > child-selector {
/* 属性: 值; */
color: #04af2f
}
子选择器示例
在这个示例中,我们更改了 div 元素的直接子元素的文本颜色。span 标签内的 para 元素保持不变,因为它不是 div 元素的直接子元素。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
.myDiv > p {
color: #04af2f;
}
</style>
</head>
<body>
<div class="myDiv">
<p>It is a paragraph element. Direct child of div element.</p>
<span><p>This is a p element inside div but not direct child of div.</p></span>
</div>
<p>This is a p element outside div.</p>
</body>
</html>
示例 2
在这个示例中,我们更改了 div 元素的直接子元素的字体大小和字体。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
.myDiv > p {
border: 2px solid #031926;
font-size: 20px;
font-family: Verdana, sans-serif;
}
</style>
</head>
<body>
<div class="myDiv">
<p>It is a paragraph element. Direct child of div element.</p>
<span><p>This is a p element inside div but not direct child of div.</p></span>
</div>
<p>This is a p element outside div.</p>
</body>
</html>