按CSS特定性排序 [英] Order by CSS Specificity

查看:96
本文介绍了按CSS特定性排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主要目标是尝试根据特异性重新排序CSS样式块。我以前曾经从 SO帮助我,我设法产生这个功能。 查看gist

My main goal is to try to reorder a CSS style block based on specificity. I previously had helped from SO and I managed to produce this function. See gist.

以下是一个示例:

function specificity($selector){
// https://gist.github.com/2774085
}

$compare = function($a, $b) use ($specificity) {
    return $specificity($a) - $specificity($b)
};

$array = css_array();

uksort($array, $compare);

以上一直工作得很好,直到我碰到这个CSS:

The above has been working great until I came across this CSS:

html, body, body div{
    background: transparent;
}
body {
    background-color: #D96F02;
}

这会重新排序为:

body { // 1 point
    background-color: #D96F02;
}
html, body, body div{ // 4 points
    background: transparent;
}

但是,这不是浏览器如何应用CSS。

However, this isn't how the browser applies the CSS.

我认为我的特异性函数可能缺少CSS的顺序的重要性,而不是基于选择器特异性的排序?这是真的吗?

I think my specificity function may be missing the importance of order of CSS rather than ordering based on selector specificity? Is this true?

我想我应该做的是在我的比较函数,添加一个额外的点 10 ,因为特异性不仅仅基于选择器,它也基于选择器的顺序。这样的东西:

I think what I should do is in my compare function, I should always add an extra points of say 10 because specificity isn't just based on selectors its based on the order of the selector too. So something like this:

 $compare = function($a, $b) use ($specificity) {
        return ($specificity($a) + 10) - $specificity($b)
    };

这是怎么样的,如何确定在这种情况下的点数? p>

How does this look and how do I determine number of points to give in this case!?

推荐答案

如果序列化,问题应该解决

The problem should go away if you serialize

html, body, body div{ 
    background: transparent; 
} 

作为单独的规则,如同以下列方式写入: p>

as separate rules, as if they were written in the following manner:

html{ 
    background: transparent; 
} 
body{ 
    background: transparent; 
} 
body div{ 
    background: transparent; 
} 

语义有点令人困惑,但基本上你是根据已合并到同一规则集中的独立选择器来判断整个声明。

The semantics is a bit confusing, but basically you are judging an entire declaration based on independent selectors that have been combined into the same rule set.

重新更新:特异性不受选择器顺序影响,即下面的规则具有相同的特异性。最后一条规则优先于以蓝色显示,除非您重新安排规则以红色显示

Re your update: specificity is not affected by selector order, i.e. the rules below have the same specificity. The last rule will take precedense rendering in blue, unless you re-arrange the rules rendering in red:

<style>
    #container span {color:red;}
    div #content {color:blue;}
</style>

<div id="container"><span id="content">Hello world!</span></div>

这篇关于按CSS特定性排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆