【问题标题】:When do I use class/id and when do I target the html tag directly [closed]我什么时候使用class/id,什么时候直接定位html标签[关闭]
【发布时间】:2013-08-09 07:29:03
【问题描述】:

我有(另一个)关于 html/css 最佳实践的问题。我检查了 web 和这个站点,但所有这些都出现在关于何时使用 ID 和何时使用类的文章中。但是,这不是我正在努力解决的问题。

我想知道何时在 html 元素选择器上使用类选择器,反之亦然。

例子:

HTML

<div class="container">
    <p class="nested-p">feefifem</p>
</div>

CSS 选项 1:

.nested-p{...}

CSS 选项 2:

.container p{...}

在什么情况下哪个选项更可取?为什么?

【问题讨论】:

标签: html css web


【解决方案1】:

第一个选项是所有 .nested-p 类(你可以把这个类放到 html ,body , p ,div and aside etc --- 好吧 - 任何你想要的。)

第二个是.container下的所有p(是的,没错,只有p

关于优先级 - 第二个更高(read this

为什么?

因为这个:

一些贴图(只是为了强调)

所以第二个看起来像这样:

而第一个看起来像:

【讨论】:

  • 但是如果你将 .container p 放在 .nested-p 之上的 css 中,它仍然会优先,如下面的 jsFiddle jsfiddle.net/KVVcF
  • .container p 的特异性为 [0 0 1 1] 但.nested-p 的特异性为 [0 0 1 0],因此.container p 优先。
  • @Charles380 正确。编辑。 (混淆了第一和第二
  • 虽然如果您创建类只是为了解决特殊性问题,那么手头就有一个更大的问题。
  • 非常酷的图片和示例。
【解决方案2】:

如前所述,样式优先级是按特定性排序的。这是一个简单的演示来说明。

HTML

<div class="container">
    <p class="nested-p">Something</p>
</div>

<div class="container">
    <p class="nested-p2">Something</p>
</div>

CSS

.nested-p {
    background: red; /* yeah right, this isn't going to be applied */
}

/* more specific */
.container .nested-p2 {
    background: green;

}

/* less specific */
.container p {
    font-size: 2em; /* will be applied to both nested p*/
    background: blue; /* only applied to the first because it is less specific than the previous declaration */
}

/* even less specific */
.nested-p2 {
    background: blue; /* will not be applied */
    font-size: 4em; /* will be applied, because it's not applied in the more specific class */
}

DEMO

【讨论】:

    【解决方案3】:

    类选择器用于将特定属性应用于 dom 元素的数量

    例子:

    <li Class="color">home</li>
    
    <li Class="color">about us</li>
    
    <li Class="color">career</li>
    
    <li Class="color">contact</li>
    

    你可以在css中写:

    .color{
    the properties u wish to apply for all
    }
    

    第二个场景是

        <div class="saikiran">
    
        <p > jsdbkabd</p>
        <p >aksdkd</p>
    
    <ul>
    
    <li>list1</li>
    
    <li>list2</li>
    
    <li>list3</li>
    
    <li>list4</li>
    
    </ul>
    </div>
    

    如果你想要前两段的特定风格,你可以使用

    .saikiran p{style u wish here}
    

    希望对你有帮助!!!快乐编码

    【讨论】:

    • 我认为 OP 更关心选择器的特异性。他们解释说他们知道如何在帖子中使用课程。
    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    • 2012-12-23
    • 2021-07-13
    相关资源
    最近更新 更多