首页 > 解决方案 > 样式属性嵌套在一个 id 一个类和另一个属性中

问题描述

我有以下 HTML 代码:

html body .section1 #red-text p {
    color: red;
}
<html>
    <head>
        <link ref="stylesheet" href="styles.css">
    </head>
    
    <body>
        <div class="section1">
            <div id="red-text">
                <p>This text should be red.</p>
            </div>
        </div>
        
        <p>This text should be left alone.</p>
    </body>
</html>

我想使用 CSS 更改“此文本应为红色”文本的颜色。我尝试了以下CSS代码无济于事:

html body .section1 #red-text p {
    color: red;
}

我在这里做错了什么?

标签: htmlcss

解决方案


正如上面其他人所说,代码在技术上是好的,但是你最好在造型时练习使用类而不是 ID!此外,正如 Mike 所说,ID 是唯一的,因此不需要前缀。

也就是说,您还没有标记为已解决,所以这可能是代码看起来更有效的样子。

`<html>
    <head>
        <link ref="stylesheet" href="styles.css">
    </head>

    <body>
        <div id="section1">
            <div id="inner-section">
                <p class="red-text">This text should be red.</p>
            </div>
        </div>

        <p>This text should be left alone.</p>
    </body>
</html>`

然后您可以简化 CSS,因为您需要为红色的任何其他文本都可以是同一个类!所以:

`.red-text {
    color: red;
}`

或者,如果您只想为该 div 中的红色文本设置样式:

`#inner-section.red-text {
    color: red;
}`

推荐阅读