假设我有下面的 HTML 代码,这里我只想更改颜色 <a>
外部 div 中的元素标签 #my_div_1
仅。
HTML:
<style>
#my_div_1 a{
color: red;
}
</style>
<div id="my_div_1">
<a href="#">change the colour </a><br>
<a href="#">change the colour </a><br>
<b> Not change my colour</b><br>
<div id="my_div_2">
<a href="#">Not change my colour </a><br>
<a href="#">Not change my colour </a><br>
</div>
<a href="#">change the colour </a> <br>
<b> Not change my colour</b> <br>
<div id="my_div_3">
<a href="#">Not change my colour </a><br>
<a href="#">Not change my colour </a><br>
</div>
<a href="#">change the colour </a> <br>
<b> Not change my colour</b> <br>
</div>
但是输出是:
不对的地方请指正。谢谢!
最佳答案
使用 >
对于 the immediate children or child combinator .和以前一样,它正在选择所有后代 <a>
(基本上所有 <a>
都嵌套在 #my_div_1
中)
Combinators
In CSS, combinators allow you to combine multiple selectors together, which allows you to select elements inside other elements, or adjacent to other elements. The four✎ available types are:
-✎最后两个被排除在外,因为我们主要关心的是后代而不是 sibling 。
The descendant selector — (space) — allows you to select an element nested somewhere inside another element (not necessarily a direct descendant; it could be a grandchild✎, for example)
✎ 这意味着术语“直系后裔”是“直系子女”的别名,因为孙子女显然是比子女更进一步的后裔。
The child selector — > — allows you to select an element that is an immediate child of another element.
…
--MDN - Simple Selectors - Combinators
<html>
<body>
<style>
#my_div_1 > a{
color: red;
}
</style>
<div id="my_div_1">
<a href="#">change the colour </a><br>
<a href="#">change the colour </a><br>
<b> Not change my colour</b><br>
<div id="my_div_2">
<a href="#">Not change my colour </a><br>
<a href="#">Not change my colour </a><br>
</div>
<a href="#">change the colour </a> <br>
<b> Not change my colour</b> <br>
<div id="my_div_3">
<a href="#">Not change my colour </a><br>
<a href="#">Not change my colour </a><br>
</div>
<a href="#">change the colour </a> <br>
<b> Not change my colour</b> <br>
</div>
</body>
</html>
关于html - 如何仅更改外部 div 中所有特定元素标签的 CSS 样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46293605/