了解css_了解CSS的特异性

了解css

Specificity in CSS refers to the how browsers determine the importance, relevance, and “seniority” of CSS styles. Here we’ll look at all the CSS styling types and use the company analogy to understand how competing styles get resolved.

CSS的特异性是指浏览器如何确定CSS样式的重要性,相关性和“高级性”。 在这里,我们将研究所有CSS样式类型,并使用公司的类比来了解如何解决竞争性样式。

CSS选择器概述 (CSS Selector Overview)

There are multiple ways to select the elements you’re trying to style in CSS. Let’s start by reviewing all the options.

有多种方法可以选择要在CSS中设置样式的元素。 让我们从检查所有选项开始。

  • Type Selectors: Select your intended element by using its element type. For example, to select all your <p> tags, use p in your CSS style sheet.

    类型选择器 :使用元素类型选择所需的元素。 例如,要选择所有<p>标记,请在CSS样式表中使用p

  • Pseudo-Elements: As the name suggests, pseudo-elements are not elements themselves but allow you to select part of your HTML relative to another selector. For example, select the first letter of each paragraph with p::first-letter.

    伪元素 :顾名思义,伪元素本身不是元素,但允许您选择HTML相对于另一个选择器的一部分。 例如,使用p::first-letter选择每个段落的p::first-letter

  • Class Selectors: Elements can have multiple classes set on them to be selected in your CSS style sheet. For example, <h1 class='header'> can be selected with .header. Multiple elements can have the same class applied to them.

    类选择器 :元素上可以设置多个类,以在CSS样式表中进行选择。 例如,可以使用.header选择<h1 class='header'> 。 多个元素可以应用相同的类。

  • Attribute Selectors: Select elements that have a specific type of attribute applied to them. For example, select inputs that accept numbers only with input[type='number'].

    属性选择器 :选择已应用特定类型属性的元素。 例如,选择仅使用input[type='number']接受数字的input[type='number']

  • Pseudo-Classes: Select elements based on the CSS state they’re in. For example, style the hovered state of a button with button:hover. Check out these previous tutorials on the :target, :hover and :active pseudo-classes to learn more.

    伪类 :根据元素所在CSS状态选择元素。例如,使用button:hover 。 查看有关:target:hover和:active伪类的这些先前教程,以了解更多信息。

  • ID Selectors: Select a specific element with its unique ID. There can only be one element with each ID, whereas classes can be applied to multiple elements. For example, select <h1 id='mainHeader'> with #mainHeader.

    ID选择器 :选择具有唯一ID的特定元素。 每个ID只能有一个元素,而类可以应用于多个元素。 例如,使用#mainHeader选择<h1 id='mainHeader'>

  • Inline Styles: Inline styles are applied to elements directly with the style attribute so you don’t actually use any CSS selectors. For example, you can make your header font color blue directly with <h1 style='color: blue;'>

    内联样式 :内联样式直接通过style属性应用于元素,因此您实际上并没有使用任何CSS选择器。 例如,您可以使用<h1 style='color: blue;'>直接将标题字体颜色设置为<h1 style='color: blue;'>

CSS选择器及其“权重” (CSS Selectors and Their “Weights”)

Each type of selector listed above has a weight. All of these can be divided into four main groups:

上面列出的每种选择器都有权重。 所有这些都可以分为四个主要组:

  • lowest weight: type and pseudo-element selectors

    最低权重 :类型和伪元素选择器

  • low weight: class, attribute, and pseudo-class selectors

    轻量级 :类,属性和伪类选择器

  • medium weight: ID selectors

    中等重量 :ID选择器

  • high weight: inline styling

    高重量 :内嵌式

If styles of differing weights are applied to the same element, the styling with the higher weight will be applied. If styles of even weights are applied, the styles that come last (nearest to the end of your style sheet) will be applied. This is due to the “cascading” effect of CSS (Cascading Style Sheets).

如果将不同权重的样式应用于同一元素,则将应用权重较高的样式。 如果应用了权重均匀的样式,则将应用最后的样式(最接近样式表的末尾)。 这是由于CSS(层叠样式表)的“层叠”效果。

For any element being styled, the last applicable block of styling with the highest weight will be applied to your element. Inline styling will trump CSS selector styling, though. 💅

对于要设置样式的任何元素,权重最高的最后一个适用样式集将应用于您的元素。 但是,内联样式将胜过CSS选择器样式。 💅

When two selectors of the same weight are applied to an element, it counts as 2x the weight. So, for example, an element selected with two classes will have a higher weight than just one in your CSS.

将两个具有相同权重的选择器应用于一个元素时,它将算作权重的2倍。 因此,例如,选择了两个类的元素将比CSS中的一个元素具有更高的权重。

.gator.cayman { // two classes
  color: purple;
}

.gator { // one class
  color: purple;
}

The main issue most of us web developers will face at some point is having multiple styles that interfere with each other. If you use a CSS framework, like Material UI, you may be trying to override some default styles. Alternately, you could have an old (and disorganized 🙈) styles.css file where you keep having to increase specificity because it’s not clear why your styles aren’t getting applied as expected.

我们大多数Web开发人员在某个时候都将面临的主要问题是多种样式会相互干扰。 如果您使用CSS框架(例如Material UI) ,则可能试图覆盖一些默认样式。 或者,您可能有一个旧的(杂乱无章的) styles.css文件,在该文件中您不得不继续提高特异性,因为尚不清楚为什么您的样式未得到预期的应用。

Like anything in web development, understanding your tools well will lead to them being used more accurately. Let’s take a look at how different combinations of selectors impact specificity and some tricks to get your styles applied as intended. 🤓

像Web开发中的任何事物一样,对工具的了解会导致它们被更准确地使用。 让我们看一下选择器的不同组合如何影响特异性,以及一些技巧以使样式按预期应用。 🤓

选择器竞争问题 (The Problem with Competing Selectors)

Understanding that different selectors have different weights is crucial for getting your CSS organized. But what if it’s not clear what has a higher weight?

了解不同的选择器具有不同的权重对于组织CSS至关重要。 但是,如果不清楚重量较高的东西怎么办?

Let’s say we have a paragraph that has two completing blocks of CSS: one with three matching classes and another block with a type attribute and two matching classes.

假设我们有一个段落,其中包含两个完整CSS块:一个具有三个匹配的类,另一个具有type属性和两个匹配的类。

For example, let’s take this input with three classes and a number type attribute applied to it.

例如,让我们使用具有三个类和一个number类型属性的输入。

<input type='number' class='gator cayman reptile'>

If we apply these competing selectors (three matching classes vs. two matching classes and an attribute), which one will get applied?

如果我们应用这些竞争的选择器(三个匹配类与两个匹配类和一个属性),将应用哪个?

.gator.cayman.reptile {
  color: purple;
}

[type='number'].gator.cayman {
  color: green;
}

In this case, the “weight” of both blocks is completely even. Attribute selectors and class selectors have the same weight and each block has three of them in total. Since they’re even, we rely on the cascading effect of CSS. The last one gets applied and the input font color will be green.🐊

在这种情况下,两个块的“权重”完全相等。 属性选择器和类选择器具有相同的权重,每个块共有三个。 由于它们是均匀的,因此我们依靠CSS的级联效果。 应用最后一种字体,输入的字体颜色将变为绿色。🐊

This gets a little more complicated when you have selectors of different weights getting mixed, though.

但是,当您混合使用不同权重的选择器时,这会变得更加复杂。

Let’s update our input to have an ID, which has a higher weight than classes and attributes.

让我们将输入更新为具有ID的ID,该ID的权重高于类和属性。

<input
  type='number'
  id='gatorInput'
  class='gator cayman reptile'>

If we have competing styles again and use the ID for one and the classes/attribute for the other, which will get applied?

如果我们再次具有竞争的样式,并且将ID用作一种样式,将class / attribute用作另一种样式,将采用哪种样式?

#gatorInput {
  color: purple;
}

[type='number'].gator.cayman.reptile {
  color: green;
}

In the first block, only one ID is being used to apply the styling. In the second block there are three classes and an attribute selector, and it comes last. Even though there are more selectors in the second block, the ID selector has a higher weight and the text will be purple! 💥

在第一个块中,仅使用一个ID来应用样式。 在第二个块中,有三个类和一个属性选择器,它位于最后。 即使第二个块中有更多选择器,ID选择器的权重也更高,文本将变为紫色! 💥

Selectors with a higher weight will always trump those with a smaller weight, even if there are multiple selectors of a lower weight. 🏋

即使有多个重量较轻的选择器,重量较高的选择器也将始终胜过重量较小的选择器。 🏋

选择器重量技巧 (Selector Weight Trick)

One trick (okay, hack 💩) in CSS when you just need a little more weight is repeating a class in the same block of CSS.

当您只需要更多权重时,CSS中的一个窍门(好的,hack💩)是在同一CSS块中重复一个类。

input.gator.gator {
  color: purple;
}

input.gator {
  color: green;
}

It might surprise you to know that the first block has a weight of two classes and the second block has a weight of one class, even though the first just repeats the class .gator. Because two classes has a higher weight than one, the input text will be purple! 🚀

知道第一个块的权重为两个类,而第二个块的权重为一个类,即使第一个块仅重复了.gator类,也可能使您感到惊讶。 因为两个类别的权重都高于一个类别,所以输入文本将为紫色! 🚀

You shouldn’t ever need to use this trick in production-level code because it’s an indicator that you have styles of very similar weights competing. Ideally, you should resolve those styles to be more clearly defined. However, this is a nice tool in your CSS toolbox when you’re in a “just make it work” mode. ✨

您永远不需要在生产级代码中使用此技巧,因为它表明您具有权重非常相似的样式竞争。 理想情况下,您应该解决这些样式以使其更清晰地定义。 但是,当您处于“使其正常工作”模式时,这是CSS工具箱中的一个不错的工具。 ✨

公司对CSS特殊性的类比 (The Company Analogy for CSS Specificity)

Specificity can sometimes feeling counter-intuitive, especially if you’re stuck in a downward spiral of adding more and more selectors to your CSS. One way I find helpful to think about specificity is by thinking of a company with clear seniority levels.

有时有时会感觉违背直觉,尤其是当您陷入向CSS中添加越来越多的选择器的螺旋式下降过程中。 我认为对特定性有所帮助的一种方法是,考虑具有清晰资历的公司。

Here are our company’s roles in order of seniority (low to high):

以下是我们公司按职位等级(从低到高)的角色:

  • employees

    雇员
  • managers

    管理者
  • directors

    导演
  • VPs

    副总裁
  • one CEO (we’ll come back to the CEO in a bit)

    一位首席执行官(过一会儿我们再回到首席执行官那里)

Let’s map these roles to our selectors now:

现在将这些角色映射到我们的选择器:

  • employees: type and pseudo-element selectors

    员工 :类型和伪元素选择器

  • managers: class, attribute, and pseudo-class selectors

    管理器 :类,属性和伪类选择器

  • directors: ID selectors

    导演 :ID选择器

  • VPs: inline styling

    VP :内联样式

Let’s look at a new example. In this case we have a paragraph with two classes and an ID.

让我们看一个新的例子。 在这种情况下,我们有一个包含两个类和一个ID的段落。

<p id='gatorParagraph' class='gator reptile'>
  blah blah blah
</p>
#gatorParagraph {
  color: purple;
}

p.gator.reptile {
  color: green;
}

We have one block that uses an ID only and another block that uses an element type (<p>) and two classes. At first glance it could be hard to know which one will get applied.

我们有一个仅使用ID的块,另一个有使用元素类型( <p> )和两个类的块。 乍一看,可能很难知道哪个将被应用。

If we use our company analogy, we have one director saying to make the text purple. On the other hand, we have an employee and two managers saying to make it green. Because the director has the highest seniority, she can trump the employee and managers’ opinions. So the text has to be purple!

如果我们使用公司的类比,我们有一位董事说将文本设为紫色。 另一方面,我们有一名员工和两名经理说要做到绿色。 由于董事的资历最高,因此她可以胜过员工和经理的意见。 因此,文字必须为紫色!

(No comment on whether this is how decisions should be made at the company 😉).

(没有评论这是否是公司做出的决定😉)。

Consider each weight level a way of escalating the decision of which styles to apply. If it can’t be decided by the selectors on the same level, escalating it will give the decision to the selector of higher seniority.

考虑每个权重级别,以一种逐步决定要应用哪种样式的方式。 如果不能由同一级别的选择者决定,则逐步升级会将决定权交给更高资历的选择者。

As a general rule, it’s best to write CSS that is specific enough you’re not going to have to find ways to keep escalating it. Be aware that once you introduce a new level of seniority, like an ID, you could be overriding other styles unintentionally too.

作为一般规则,最好编写足够具体CSS,而不必寻找不断升级的方法。 请注意,一旦您引入了新的资历级别(例如ID),您也可能会无意间覆盖其他样式。

重要的是首席执行官 (!important is the CEO)

So far we haven’t discussed who our company’s CEO is in this analogy for CSS specificity. What’s higher than inline styling? The !important rule!

到目前为止,我们还没有讨论过用CSS特异性来比喻我们公司的首席执行官。 有什么比内联样式高? !important规则!

Using our same example as before, let’s add !important to the block that previously had a lower weight/seniority.

使用与之前相同的示例,让我们将!important添加到以前具有较低权重/优先级的块中。

#gatorParagraph {
  color: purple;
}

p.gator.reptile {
  color: green !important;
}

Adding !important will always escalate the seniority to be the highest possible level. With our company analogy, we now have a director vs. an employee, two managers, and the CEO. As soon as the CEO is introduced, she can trump anything else being suggested. 💣

!important总是会把资历提升到可能的最高水平。 与我们的公司类似,我们现在有一个董事与一个雇员,两个经理和一个首席执行官。 引入首席执行官后,她可以胜过其他任何建议。 💣

请不要使用!important (Please Don’t Use !important)

The !important rule is a slippery slope and seeing it in your CSS styles is generally a red flag that the specificity needs to be reorganized. It is rare that there will be an element that can only be styled by nuking the rest of your CSS rules that would otherwise be applied.

!important规则很滑,在您CSS样式中看到它通常是一个危险信号,那就是需要重新组织特异性。 很少有元素只能通过对其余CSS规则进行样式化来设置样式,否则将应用这些规则。

Once you introduce !important, it often leads to being overused like in the example below. The !importants cancel each other out and you’re back to having to understand the weight and cascading effect of each block.

一旦引入!important ,它通常会导致被过度使用,如以下示例所示。 !important相互抵消了,您又回到了必须了解每个块的重量和级联效果的位置。

#gatorParagraph {
  color: purple !important;
}

p.gator.reptile {
  color: green !important;
}

Instead of using the !important rule, try opening your dev tools in the browser to get a better understanding of which styles are interfering with your new ones.

不要尝试使用!important规则,而是尝试在浏览器中打开您的开发工具,以更好地了解哪些样式正在干扰您的新样式。

Once you know what styles are causing you trouble, you can either add additional selectors of the same level of weight, or update your markup to use different selectors. 🌈

一旦知道造成麻烦的样式,就可以添加权重相同的其他选择器,也可以更新标记以使用不同的选择器。 🌈

Using !important will often inevitably lead to having competing CSS styles that both use !important. 🙈

使用!important通常会不可避免地导致具有都使用!important的竞争CSS样式。 🙈

通用选择器和组合器 (Universal Selector and Combinators)

The universal selector (*) and combinators do not impact the weight of your selectors. Combinators include child selectors (>), general sibling selectors (~), and adjacent sibling selectors (+).

通用选择器( * )和组合器不会影响选择器的重量。 组合器包括子选择器( > ),常规同级选择器( ~ )和相邻的同级选择器( + )。

For example, if we have a paragraph with two spans, using a child combinator will not increase the specificity over not using it:

例如,如果我们有一个包含两个跨度的段落,则使用子组合器不会比不使用子组合器增加特异性:

<p id='gatorParagraph'>
  <span class='reptile'>eggs</span>
  <span class='reptile'>nest</span>
</p>
#gatorParagraph > .reptile {
  color: purple;
}

#gatorParagraph .reptile{
  color: green;
}

These blocks of CSS has the same specificity – the child combinator makes no difference – so the text will be green.

这些CSS块具有相同的特异性-子组合器没有区别-因此文本将变为绿色。

One of the best visuals for understanding CSS specificity is called specifishity, by Estelle Weyl. Check it out! 🤓

Estelle Weyl认为理解CSS特异性的最好的视觉手段之一是“ 特殊性” 。 看看这个! 🤓

Also, if you’re not keen on adding up specificity weights yourself, there’s a specificity calculator that will do the math for you. 🥳

另外,如果您不希望自己增加特异性权重,则可以使用特异性计算器为您完成数学运算。 🥳

翻译自: https://www.digitalocean.com/community/tutorials/css-understanding-specificity-in-css

了解css

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值