html - 如何仅更改外部 div 中所有特定元素标签的 CSS 样式?

标签 html css css-selectors

假设我有下面的 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>

但是输出是:

enter image description here

不对的地方请指正。谢谢!

最佳答案

使用 >对于 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/

相关文章:

css - 使用 Sass 将另一个元素类型添加到定义中§

html - 如何让 MJML <mj-text> 元素显示 inline-block

css - Chrome 移动设备上的字体问题,字体大小变大

css - 第 nth-of-type 与不同元素列表中的目标类的行为不正确

html - 如何仅滚动第二个没有指定高度的div

javascript - 如何将 DIV 的大小调整为小于其初始宽度和高度?

javascript - querySelector 'tbody > tr[data-index=-1]' 问题

html - 嵌套选项卡之间的空间

html - 我不知道为什么我的代码导航栏文本颜色没有改变?

javascript - 如何在 diff 文本区域中显示 php 获取的值?