CSS :deep
在CSS中,:deep
伪类选择器用于选择一个元素及其所有后代元素,无论它们在DOM中的位置如何。这个选择器通常用于在Shadow DOM中选择元素。
1. 基本语法
:deep
伪类选择器的基本语法如下:
:host-context(:deep selector) {
/* styles */
}
其中 :deep
用于选择所有后代元素,selector
是要选择的元素的选择器。
2. 示例代码
2.1 选择所有后代元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>:deep 示例</title>
<style>
:host-context(:deep .container) {
color: red;
}
</style>
</head>
<body>
<div class="container">
<div>
<p>这是一个段落</p>
</div>
</div>
</body>
</html>
Output:
在上面的示例中,:deep .container
选择了所有后代元素中具有 container
类的元素,并将其文字颜色设置为红色。
2.2 选择所有后代元素中的链接
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>:deep 示例</title>
<style>
:host-context(:deep a) {
text-decoration: none;
color: blue;
}
</style>
</head>
<body>
<div>
<a href="#">这是一个链接</a>
</div>
</body>
</html>
Output:
在这个示例中,:deep a
选择了所有后代元素中的链接,并将它们的文本颜色设置为蓝色,并去掉了下划线。
2.3 选择所有后代元素中的特定类
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>:deep 示例</title>
<style>
:host-context(:deep .special) {
font-weight: bold;
}
</style>
</head>
<body>
<div>
<p class="special">这是一个特殊的段落</p>
</div>
</body>
</html>
Output:
在这个示例中,:deep .special
选择了所有后代元素中具有 special
类的元素,并将它们的字体加粗。
3. 结语
通过 :deep
伪类选择器,我们可以方便地选择元素及其所有后代元素,使得样式的应用更加灵活和方便。