CSS仅匹配ID中的特定标签

时间:2013-12-08 17:31:12

标签: html css

有人可以告诉我如何使这项工作。在下面的代码中,我需要#awesome_body ID中的h1 / h2 / h3 / .tiny为红色。 #awesome_body内的任何h1 / h2 / h3 / .tiny都应该使用浏览器的默认颜色:

<body>
    <div id="awesome_body">
        <div id="show_body">
            <span>SHOWING YOUR...</span>
            <h1> AWESOME BODY!</h1>
            <h2> AWESOME BODY!</h2>
            <h3> AWESOME BODY!</h3>
            <span class="tiny"> AWESOME BODY!</span>
        </div>
    </div>
    <br/>
    <br/>
    <div id="cool_body">
        <div id="show_body">
            <span>SHOWING YOUR...</span>
            <h1> COOL BODY!</h1>
            <h2> COOL BODY!</h2>
            <h3> COOL BODY!</h3>
            <span class="tiny"> COOL BODY!</span>
        </div>
    </div>
</body>

#awesome_body h1, h2, h3,.tiny {
    color: red;
}
.tiny{
    font-size: 10px;
}

JSFiddle http://jsfiddle.net/webteckie/q4FLd/3/

enter code here

2 个答案:

答案 0 :(得分:3)

您将使用以下内容:

Updated jsFiddle example

#awesome_body h1, #awesome_body h2, #awesome_body h3, #awesome_body .tiny {
    color: red;
}

答案 1 :(得分:1)

您应该为所有选择器添加容器div的id前缀,如下所示:

#awesome_body h1, #awesome_body h2, #awesome_body h3, #awesome_body .tiny {
    color: red;
}

如果您想选择direct child,那么:

#awesome_body > h1, #awesome_body > h2, #awesome_body > h3, #awesome_body > .tiny {
    color: red;
}

这将确保

<div id="awesome_body">
    <div>
       <h2>Text</h2> // is not red
    </div>
    <h2>text</h2> // is red
</div>