首页 > web前端 > css教程 > 掌握 CSS:了解级联

掌握 CSS:了解级联

WBOY
发布: 2024-07-17 09:33:39
原创
536 人浏览过

Mastering CSS: Understanding the Cascade

层叠样式表 (CSS) 是 Web 的一项基础技术,允许开发人员控制 HTML 文档的视觉呈现。虽然 CSS 语法乍一看似乎很简单,但应用和继承样式的方式可能出奇地复杂。理解这些复杂性对于编写高效、可维护和可预测的 CSS 至关重要。
在这份综合指南中,我们将探讨 CSS 的级联和继承概念。

CSS 级联

级联是当存在多个冲突规则时确定将哪些 CSS 规则应用于元素的算法。了解级联的工作原理对于编写按预期运行的 CSS 至关重要。级联按以下顺序考虑多个因素:

  • 1 样式表来源
  • 2 种内联样式
  • 3 选择器特异性
  • 4 源订单

为了完全详尽,我们可以添加:

  • 2.5 在图层中定义的样式阅读更多
  • 3.5 作用域为 DOM 一部分的样式阅读更多

让我们按优先顺序分解影响级联的因素:

1. 样式表起源

CSS 可以来自三个不同的来源:

  • 1 用户代理样式:这些是浏览器的默认样式。每个浏览器都有自己的一组默认样式,这就是为什么无样式的 HTML 在不同浏览器中看起来会略有不同。
  • 2 用户样式:这些是用户设置的自定义样式。虽然很少见,但某些用户可能会使用自定义样式表来覆盖默认样式以实现可访问性或个人偏好。
  • 3 作者样式:这些是您作为 Web 开发人员编写的样式。

通常,作者样式优先于用户样式,而用户样式又会覆盖用户代理样式。这允许开发人员自定义元素的外观,同时在必要时仍然尊重用户的偏好。

2. 内联样式

使用 style 属性直接应用于元素的样式具有非常高的优先级:

<p style="color: red;">This text will be red.</p>
登录后复制

内联样式将覆盖外部样式表或

使用内联样式通常不鼓励,因为它将演示与内容混合在一起并使样式更难维护。

3. 选择器特异性

特异性是CSS中的一个关键概念,它决定了当存在多个冲突规则时将哪些样式应用于元素。每个 CSS 选择器都有一个特异性编号,可以通过计算该编号来预测哪些样式将优先。

特异性通常表示为四部分数字 (a,b,c,d),其中:

  • a:内联样式数量(一般省略)
  • b:ID选择器的数量
  • c:类选择器、属性选择器和伪类的数量
  • d:元素选择器和伪元素的数量

结果数字不是以 10 为基数。相反,请将其视为从左到右比较的单独列。请参阅示例:

  • p = (0,0,0,1)
  • .class = (0,0,1,0)
  • #id = (0,1,0,0)
  • 行内样式 = (1,0,0,0)

考虑这两个相互冲突的规则:

#header .nav li { color: blue; } /* (0,1,1,1) */ 
nav > li a { color: red; } /* (0,0,0,3) */
登录后复制

第一条规则 (0,1,1,1) 具有更高的特异性,因此文本将为蓝色。

伪类选择器(例如 :hover)和属性选择器(例如 [type="text"])都具有与类选择器相同的特异性。

通用选择器 (*) 和组合符 (>, +, ~) 不影响特异性。

此外,:not() 伪类也不会增加特异性值;仅计算其中的选择器。

一些在线工具可以帮助计算特异性 (https://specity.keegan.st/)。

4. 来源顺序

如果其他条件相同,则样式表中稍后出现的规则优先:

.button { background-color: blue; }
.button { background-color: green; }  /* This one wins */
登录后复制

在此示例中,按钮将具有绿色背景。

强大的覆盖

虽然理解级联对于编写可维护的 CSS 至关重要,但还有一个难题可以覆盖我们迄今为止讨论的所有规则:!important 关键字。

!important 的工作原理

!important 关键字可以覆盖级联中的所有其他注意事项,除了其他具有更高源优先级的 !important 声明。

/* styles.css */ 
.button {
  background-color: blue !important;
}
登录后复制
<!-- index.html -->
<head>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <button style="background-color: red"> My button </button> 
    <!-- The color will be blue due to !important above -->
</body>
登录后复制

In this example, even though inline styles usually have the highest priority, the button will still have a blue background because of the !important declaration.

The Cascade and !important

The !important keyword actually introduces additional layers to the cascade. The full order of precedence, from highest to lowest, is:

  • User agent important declarations
  • User important declarations
  • Author important declarations
    • Important Inline styles
    • Important not inlined styles
  • Author normal declarations
    • Inline styles
    • Not inlined styles
  • User normal declarations
  • User agent normal declarations

When to Use it

While !important can be tempting as a quick fix, it's generally considered a last resort. Overuse can lead to specificity wars and make your CSS harder to maintain. Legitimate use cases include:

  • Overriding third-party styles you can't modify
  • Creating utility classes that should always apply
  • Ensuring critical accessibility styles are applied

A Potential Solution To Simplify Specificity Management

If you find yourself using !important often, consider refactoring your CSS to use more specific selectors or a more modern approach like utilising :is() and :where() to write more flexible and maintainable styles. (I talk about these two in more details here)

Also, the @layer at-rule, which is fairly supported, allows you to create "layers" of styles with explicitly defined order of precedence:

@layer base, components, utilities;

@layer utilities {
  .btn { padding: 10px 20px; }
}

@layer components {
  .btn { padding: 1rem 2rem; }
}
登录后复制

This offers a more structured approach to managing style precedence without resorting to !important or engaging in a specificity arms race. However, I haven’t used this in a production project myself, if you do, I’d love to hear about your experience :)

Inheritance

Passing Styles Down the DOM Tree

Inheritance is another fundamental concept in CSS. Some CSS properties are inherited by default, meaning child elements will take on the computed values of their parents. This is particularly useful for text-related properties like color, font, font-family, font- size, font-weight, font-variant, font-style, line-height, letter-spacing, text-align, text-indent, text-transform, white-space, and word-spacing.

body {
  font-family: Arial, sans-serif;
  color: #333;
  line-height: 1.5;
}
登录后复制

In this example, all text within the body will inherit these styles unless explicitly overridden. This allows for efficient styling of document-wide typography without having to repeat rules for every element.

A few others inherit as well, such as the list properties: list-style, list-style-type, list-style-position, list-style-image, and some other table related properties

Not all properties are inherited by default. For example, border and padding are not inherited, which makes sense – you wouldn't want every child element to automatically have the same border as its parent.

Inheritance keywords

CSS provides several keywords to give you fine-grained control over inheritance and to reset styles:

  • The inherit keyword forces a property to inherit its value from its parent element (This can be useful for properties that don't inherit by default, like border in this example).
  • The initial keyword resets a property to its initial value as defined by the CSS specification (This can be helpful when you want to completely reset an element's styling).
  • The unset keyword acts like inherit for inherited properties and initial for non-inherited properties (This provides a flexible way to reset properties without needing to know whether they're inherited or not).
  • The revert keyword resets the property to the value it would have had if no author styles were applied (This is useful when you want to fall back to browser defaults rather than CSS-defined initial values).

The initial and unset keywords override all styles, affecting both author and user-agent stylesheets. This means they reset the element's styling to its default state, ignoring any previous styling rules applied by the author or the browser.

However, there are scenarios where you only want to reset the styles you’ve defined in your author stylesheet, without disturbing the default styles provided by the browser (user-agent stylesheet). In such cases, the revert keyword is particularly useful. It specifically reverts the styles of an element back to the browser’s default styles, effectively undoing any custom author-defined styles while preserving the inherent browser styling.

请注意,使用速记属性时省略的值会隐式设置为其初始值。这可能会覆盖您在其他地方设置的其他样式。

总结

通过理解级联、继承和现代 CSS 功能的复杂性,您将能够更好地编写高效、可维护且强大的样式表。请记住,CSS 不仅仅是让事物看起来更漂亮,它还在于创建可在各种设备和浏览器上工作的健壮、灵活的设计。

以上是掌握 CSS:了解级联的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板