强制选择器使用样式,无论它在dom中的哪个位置

时间:2013-09-22 15:23:24

标签: css private

我想要定义一个编号的圆圈,如下所示:

enter image description here

http://jsfiddle.net/edi9999/6QJyX/

.number
{
    border-radius: 50%;
    width: 32px;
    height: 24px;
    text-align: center;
    padding-top:8px;
    font-size: 14px;
    display:inline-block;
    line-height: 16px;
    margin-left:8px;
    color:white;
    background-color:black;
    border-color:white;
}

我想将重要性添加到选择器,以便无论元素在什么上下文中,具有类号的元素看起来都相同。

以下是代码破解的示例:http://jsfiddle.net/edi9999/6QJyX/2/

这样做的方法是在CSS的所有属性中添加!important,但我想知道它们是否可能是其他解决方案,因为它有点糟糕。

我添加了私有标记,因为它看起来有点像代码封装。

2 个答案:

答案 0 :(得分:0)

您最好的选择是增加选择器的特异性。除此之外,你无能为力。

#id .number

ID选择器将增加特异性,以便只有选择器中的另一个ID才能覆盖它。

http://jsfiddle.net/6QJyX/3/

答案 1 :(得分:0)

增加选择者的特异性只会导致specificity wars(这会导致愤怒,导致仇恨,从而导致痛苦)。我建议 de 提高引起问题的选择器的特异性。

下面的伪代码:

.number {...}
.card span {...} // this selector is questionable
<div.number> this is styled correctly </div>
<div.card>
    <span.number> this is styled incorrectly </span>
</div>

为什么所有 .card span需要以特定方式设置样式?似乎第二个选择器是more like a grenade and less like a sniper - 也就是说,它定位的是一组元素,而不仅仅是你需要的元素。