【问题标题】:How can I set css for a class in a class?如何为班级中的班级设置css?
【发布时间】:2011-09-09 04:34:15
【问题描述】:

使用此 HTML 代码。

<div class="noote">
    <p class="first admonition-title">Noote</p>
    <p class="last">Let's noote.</p>
</div>

如何使用 css 将 Noote 的颜色设置为红色? 我的意思是,如何使用 css 为 (div class="noote") 和 (p class="first") 设置一些东西?

【问题讨论】:

  • 你想将所有具有“noote”类的DIV设置为红色吗?

标签: html css css-selectors


【解决方案1】:

试试这个:

/*this will apply for the element with class first 
inside the element with class noot */

.noote .first{    
    color:red;
}

/* If you wanted to apply a rule for both individually
you can do: */

.noote, .first{    
    border:1px solid red;
}

【讨论】:

    【解决方案2】:
    div.note{
       ...
    }
    

    指具有类注释的 div 元素。

    p.first{
        ...
    }
    

    指第一个具有类的p元素。

    div.note p.first{
        ...
    }
    

    指的是note里面第一个类的p元素。

    另外,如果你想设置一个元素子元素而不给它设置一个类,

    div.note p:first-child{
        /* it refers to the first p that contains noote */
    }
    

    【讨论】:

    • OP 询问如何引用.first inside .noote,而不仅仅是单独引用。
    • 不,这不是使用:first-child 的正确方法。正确的方法是div.note p:first-child。详情请见stackoverflow.com/questions/4195161/…
    • 第一次看没看懂 :) 谢谢指正 :) ..我会更新我的答案
    【解决方案3】:

    @amosrivera 知道了。

    值得注意的是后代选择器需要更多的 CPU。我总是尽可能使用更具体的规则。所以不是

    .noote .first{
        backgorund:red;
    }
    

    你可以说

    .noote > .first{
        backgorund:red;
    }
    

    在大多数情况下只是名义上的差异,但仍然是一个好习惯。

    真的吗?

    后代选择器是 低效... 越不具体 key,节点数越大 需要评估。

    ——Google "Let's make the web faster" docs

    后代选择器是一个主要的慢 下到 Safari 浏览器

    ——John Sykes, May 2008

    一些性能测试显示little impact,大多数作者都同意它只对非常大的文档有影响。

    但主要是,我只是按照我的程序员本能 - 说出你的意思,仅此而已。

    【讨论】:

    • 这看起来确实很有趣,你有一个链接可以证明这种性能差异吗?
    猜你喜欢
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多