css样式表覆盖规则_使用这三种CSS方法来驯服不规则的样式表

css样式表覆盖规则

Tame Unruly Style Sheets With These Three CSS Methodologies

This article is part of a series created in partnership with SiteGround. Thank you for supporting the partners who make SitePoint possible.

本文是与SiteGround合作创建的系列文章的一部分。 感谢您支持使SitePoint成为可能的合作伙伴。

In this article, I’m going to discuss three successful approaches to CSS architecture, their principles, goals and advantages.

在本文中,我将讨论CSS架构的三种成功方法,其原理,目标和优势。

为什么CSS代码会螺旋失控? (Why Can CSS Code Spiral Out of Control?)

Keeping CSS code lean, re-usable and maintainable is notoriously hard. If you neglect to enforce any coding and organizational rules in a consistent way, this can be the case both for small and medium to big projects, where more than one developer is at work.

保持CSS代码精简,可重用和可维护非常困难。 如果您忽略以一致的方式执行任何编码和组织规则,则对于不止一个开发人员在工作的中小型到大型项目,情况都是如此。

Where the codebase is large, goes through a number of changes over time, and organization is lacking, it often happens that teams prefer to add new style rules at the end of the style sheet document rather than remove chunks of it or modify what’s already there. The main reason is often that the effects of editing or removing CSS declarations can be unpredictable and risk breaking the design somewhere in the project. This is a losing strategy, which can lead to code duplication, specificity issues where overriding style rules turns into a battle, and overall bloat.

在代码库很大,随着时间的推移经历了许多更改且缺乏组织的情况下,经常会发生这样的情况:团队宁愿在样式表文档的末尾添加新的样式规则,而不是删除其中的块或修改已有的样式。 主要原因通常是编辑或删除CSS声明的效果不可预测,并有可能破坏项目中某个地方的设计。 这是一个失败的策略,它可能导致代码重复,导致覆盖样式规则变成一场战斗的特异性问题以及整体膨胀。

Most often than not, choosing the methodology that most suits your needs is an iterative process, which starts with getting familiar with what’s already out there.

通常,选择最适合您的需求的方法是一个迭代过程,首先要熟悉已经存在的方法。

Here are three methodological approaches to help you fight the challenges of a messy style sheet.

以下是三种方法方法,可帮助您应对凌乱的样式表的挑战。

边界元 (BEM)

Block-Element-Modifier or BEM methodology.

BEM stands for Block-Element-Modifier. It is a methodology for architecting CSS created by Yandex.

BEM代表Block-Element-Modifier 。 这是Yandex创建的用于架构CSS的方法。

The goal of the BEM methodology is

BEM方法论的目标是

to develop sites which should be launched fast and supported for a long time. It helps to create extendable and reusable interface components.

开发应该快速启动并得到长期支持的站点。 它有助于创建可扩展和可重用的接口组件。

BEM website

BEM网站

The key concepts here are easy project maintenance over time, and components reusability.

这里的关键概念是随着时间的推移易于进行项目维护以及组件的可重用性

The core BEM strategy consists in organizing CSS code into reusable modules with the help of a smart naming convention. Let’s have a closer look.

BEM的核心策略是在智能命名约定的帮助下将CSS代码组织成可重用的模块。 让我们仔细看看。

什么是街区? (What Is a Block?)

Identifying blocks is a crucial step of applying the BEM methodology. A block is a

识别块是应用BEM方法的关键步骤。 块是一个

functionally independent page component that can be reused. In HTML, blocks are represented by the class attribute.

功能上独立的页面组件,可以重复使用。 在HTML中,块由class属性表示。

BEM docs.

BEM文档

When deciding what to consider a block, ask yourself if you can easily remove that portion of code and use it somewhere else. For instance, you can consider a website header or footer to be a block.

在决定考虑使用什么块时,请问自己是否可以轻松删除那部分代码并在其他地方使用它。 例如,您可以将网站的页眉或页脚视为一个块。

You can safely nest blocks, for instance, you can place a menu block inside a header block.

您可以安全地嵌套块,例如,可以将菜单块放置在标题块中。

<header>
<ul class="menu">
<!-- menu items here -->
</ul>
</header>

Because in principle you should be able to reuse blocks anywhere in your page, your CSS for the block should not set any margins or positioning rules.

因为原则上您应该能够在页面的任何地方重用块,所以块CSS不应设置任何边距或定位规则。

Finally, when choosing a name, make sure the name describes what the block is for, what its purpose is, never what its appearance or state is. In other words, its name should answer the question: What is it? (e.g., a header, a menu, etc.), not What does it look like? (e.g., fixed header, small menu, etc.).

最后,在选择名称时,请确保该名称描述了该块的用途,目的,而不是其外观或状态。 换句话说,其名称应回答以下问题: 它是什么? (例如标题,菜单等),不是什么样子? (例如,固定的标题,小菜单等)。

什么是元素? (What Is an Element?)

According to the BEM methodology, an Element is

根据BEM方法论,元素是

A part of a block that has no standalone meaning and is semantically tied to its block.

块的一部分,没有独立的意义,并且在语义上与其块相关。

Get BEM

获取BEM

Here are a few principles applying to elements:

以下是适用于元素的一些原则:

  • Elements only live inside a block

    元素仅存在于块内
  • Elements cannot belong to other elements, they can only be part of a block

    元素不能属于其他元素,它们只能是块的一部分
  • You can build nested elements

    您可以构建嵌套元素
  • Element names describe their purpose, not their appearance

    元素名称描述其用途,而不是其外观
  • When naming elements, you need to follow this conventions: block__element

    在命名元素时,您需要遵循以下约定: block__element

什么是修饰符? (What Is a Modifier?)

A Modifier is

修饰符是

An entity that defines the appearance, state, or behavior of a block or element.

定义块或元素的外观,状态或行为的实体。

BEM docs

BEM文档

For instance, a header block can be fixed to the top of the page, an accordion block can be open or closed, a button block can be disabled, etc.

例如,页眉块可以固定在页面顶部 ,手风琴块可以打开关闭 ,按钮块可以禁用 ,等等。

The BEM naming convention for modifiers looks like this: block__element_modifier.

BEM修饰符的命名约定如下所示: block__element_modifier

This is the core of the BEM methodology. In addition, BEM offers principles of file structure organization, a suite of tools, and a lively community for support.

这是BEM方法论的核心。 此外,BEM还提供了文件结构组织原则, 一套工具以及一个活跃的社区来提供支持。

使用BEM的优点 (Pros of Using BEM)

These are some advantages of using BEM in your projects

这些是在项目中使用BEM的一些优点

  • New developers can quickly understand the relationship between a component in markup and CSS rules

    新开发人员可以快速了解标记中的组件与CSS规则之间的关系
  • It facilitates productivity in teams. The benefit is especially noticeable when working on larger projects

    它提高了团队的生产力。 在较大的项目上工作时,好处尤其明显
  • The naming convention reduces the risks of class name collisions and style leaks

    命名约定降低了类名冲突和样式泄漏的风险
  • CSS is not closely tied to the markup in a specific location inside the page

    CSS与页面内特定位置的标记没有紧密联系
  • CSS is highly reusable

    CSS是高度可重用的

SMACSS (SMACSS)

Scalar Modular Architecture for CSS or SMACSS

Scalable and Modular Architecture for CSS, or SMACSS, is a web development methodology for organizing and writing CSS code. Its creator, Jonathan Snook, describes it as follows:

CSS的可扩展和模块化体系结构,或SMACSS,是一种用于组织和编写CSS代码的Web开发方法。 它的创建者乔纳森·斯努克(Jonathan Snook)对它的描述如下:

SMACSS is a way to examine your design process and as a way to fit those rigid frameworks into a flexible thought process. It is an attempt to document a consistent approach to site development when using CSS.

SMACSS是检查您的设计过程的一种方法,也是将那些刚性框架纳入灵活的思想过程的一种方法。 这是尝试记录使用CSS时网站开发的一致方法。

SMACSS Website

SMACSS网站

At its core is a way of categorizing CSS rules. Categorization brings forth patterns, i.e., things you see repeated more than once in the design, around which you can work out guidelines for coding maintainable and reusable CSS.

其核心是对CSS规则进行分类的方法。 分类带来了模式,即您在设计中看到的重复多次,围绕这些模式,您可以制定出可维护和可重用CSS编码的准则。

SMACSS core categories are:

SMACSS核心类别为:

  • Base — In this category belong CSS rules that govern the default appearance of elements. Selectors include single element selectors, attribute selectors, pseudo-class selectors, sibling selectors, etc. For instance, html, body, a, a:hover, etc.

    基本 —此类别中CSS规则管理元素的默认外观。 选择器包括单个元素选择器,属性选择器,伪类选择器,同级选择器等。例如htmlbodya, a:hover等。

  • Layout — This category is for styles used to divide the page into sections.

    布局 -此类别是用于将页面分为几部分的样式。

  • Module — Modules are the reusable lego-like parts of the design, e.g., menu, dialog, search box, etc.

    模块 -模块是设计中可重复使用的乐高类部件,例如菜单,对话框,搜索框等。

  • State — This category includes styles to describe what the layout or modules look like when in a particular state (e.g., visible or hidden, expanded or closed, etc.) or in a particular view (e.g., Home page or inner page)

    状态 -此类别包括样式,用于描述处于特定状态(例如,可见或隐藏,展开或关闭等)或处于特定视图(例如,主页或内页)时布局或模块的外观

  • Theme — this category is similar to State in so far as it includes CSS rules that take care of layouts’ and modules’ appearance. Not all projects need this extra category, but it’s good to know it’s there.

    主题(Theme) –该类别与State(状态)相似,因为它包含照顾布局和模块外观CSS规则。 并非所有项目都需要这个额外的类别,但是很高兴知道它在那里。

SMACSS命名约定 (SMACSS Naming Convention)

Related to the categories outlined above, SMACSS proposes a naming convention to help with code organization and dev teams productivity.

与上面概述的类别相关,SMACSS提出了一个命名约定,以帮助代码组织和开发团队提高工作效率。

Layout, State and Module rules are prefixed with a meaningful name or abbreviation.

布局,状态和模块规则以有意义的名称或缩写为前缀。

For Layout rules, something like layout-, grid-, or even simply l- are acceptable prefixes.

对于布局规则,可以使用诸如layout-grid-甚至只是l-类的前缀。

For State rules, the convention is to prefix the state with is-, e.g., is-hidden, is-visible, etc.

对于状态规则,约定是在状态前添加is- ,例如is-hiddenis-visible等。

As for Modules, just use the name of the component you’re building, e.g., .menu, .dialog, etc.

至于模块,只需使用您要构建的组件的名称,例如.menu.dialog等。

For instance, to style an open dialog box, you can use a selector like .dialog.is-open in your CSS. Related elements inside a module, as well as variations of the same module, should use the module’s base name as a prefix. Also, try not to use Ids, element selectors, or nested selectors. For instance, to select a menu item inside a module called menu, instead of writing your selector like this: .menu li a, use something like this: .menu-link or .menu-item.

例如,要设置打开对话框的样式,可以在CSS中使用.dialog.is-open类的选择器。 模块内的相关元素以及同一模块的变体应使用模块的基本名称作为前缀。 另外,请尽量不要使用ID,元素选择器或嵌套选择器。 例如,要在名为menu的模块中选择菜单项,而不是像这样编写选择器: .menu li a ,请使用如下内容: .menu-link.menu-item

Unlike BEM, SMACSS doesn’t prescribe an overly-strict naming convention. Jonathan Snook makes this clear as he claims:

与BEM不同,SMACSS并未规定过于严格的命名约定。 乔纳森·斯努克(Jonathan Snook)明确指出:

… don’t feel like you have to stick to these guidelines rigidly. Have a convention, document it, and stick to it.

……您不必严格遵守这些准则。 有一个约定,记录下来并坚持下去。

SMACSS Website

SMACSS网站

使用SMACSS的优势 (Advantages of Using SMACSS)

Some advantages of the SMACSS approach to CSS coding are:

SMACSS方法用于CSS编码的一些优点是:

  • It offers valid guidelines for modular, maintainable CSS while avoiding to be overly-prescriptive

    它为模块化,可维护CSS提供了有效的准则,同时避免了过于规范的要求
  • You can learn (and teach) SMACSS quickly

    您可以快速学习(和教授)SMACSS
  • SMACSS naming convention is less verbose and in some ways easier to come to grips with than BEM’s

    SMACSS命名约定不那么冗长,并且在某些方面比BEM更容易掌握
  • It’s flexible enough to work well for both large and small projects

    它足够灵活,可以很好地适用于大型和小型项目

电子安全系统 (ECSS)

Enduring CSS or eCSS methodology.

Enduring CSS or eCSS is

持久CSS或eCSS是

A guide to writing style sheets for large scale, rapidly changing, long-lived web projects.

编写样式表的指南,用于大型,快速变化的长期Web项目。

eCSS Website

eCSS网站

This CSS methodology has really piqued my interest for the original perspective taken by its author, Ben Frain, on the challenge of dealing with CSS at scale.

这种CSS方法确实引起了我的兴趣,即它的作者Ben Frain对大规模处理CSS的挑战所持的原始观点。

A central concept of eCSS is isolation. Isolation means that each component is an insulated unit of code with no dependency, no contextual baggage, reusable and removable without risk of causing style leaks.

eCSS的中心概念是隔离 。 隔离意味着每个组件都是一个隔离的代码单元,没有依赖关系,没有上下文包,可重复使用和可移动,没有引起样式泄漏的风险。

This is achieved mainly by

这主要是通过

  • Encapsulating all the code, not just CSS, but all the technologies you need to build each component, in its own shared folders.

    将所有代码(不仅是CSS)封装,而且还将构建每个组件所需的所有技术封装在其自己的共享文件夹中。
  • Creating a brand new component each time you need a component similar to one already in place, but with some variations, even if the variations are slight.

    每次需要一个与已经存在的组件相似但有一些变化的组件时,都创建一个全新的组件,即使这些变化很小。
  • Using a strict CSS naming convention

    使用严格CSS命名约定

On the basis of the second point above, it seems clear that repeating properties and values are not a problem for eCSS. In this regard, eCSS represents a radical departure from methodologies like BEM and SMACSS, which extend or abstract from the existing component thereby avoiding, or trying as best they can to avoid, code repetition.

根据以上第二点,很明显,对于eCSS而言, 重复属性和值不是问题。 在这方面,eCSS代表了与BEM和SMACSS之类的方法的根本偏离,后者从现有组件进行扩展或抽象,从而避免或尽其所能避免代码重复。

Does this mean eCSS produces heavy style sheet files? Not necessarily. After some tests using file compression, Ben Frain came to the conclusion that, due to the fact that ‘gzip is incredibly efficient at compressing repetitive strings’, the difference in terms of file size between using eCSS and other methodologies that favor abstraction over repetition were super tiny.

这是否意味着eCSS会生成大量样式表文件? 不必要。 经过一些使用文件压缩的​​测试之后,Ben Frain得出的结论是,由于“ gzip压缩重复字符串的效率令人难以置信”,因此使用eCSS和其他支持抽象而不是重复的方法之间在文件大小方面的差异是超小。

使用eCSS的好处 (Benefits of Using eCSS)

Here’s what you can gain from applying the eCSS methodology and embracing its view of repetition:

通过应用eCSS方法并接受其重复视图,您可以从中获得好处:

  • By keeping each visual pattern isolated, the CSS code becomes easier to maintain

    通过使每个可视模式保持隔离,CSS代码变得更易于维护
  • Although you find repeated properties and values, file size increases remain minimal in the long run. This is so because modules are self-contained, isolated units that you can quickly remove when you don’t need them anymore, without fear of breaking the design

    尽管您发现重复的属性和值,但从长远来看,文件大小的增加仍然保持最小。 之所以如此,是因为模块是独立的,独立的单元,您可以在不再需要它们时快速删除它们,而不必担心破坏设计
  • All language/technology files necessary to create a module share the same folder, making both editing and physically removing what’s no longer needed, extremely easy.

    创建模块所需的所有语言/技术文件都共享同一文件夹,这使编辑和物理删除不再需要的文件变得非常容易。

You can read all the details of this innovative methodology in Frain’s book Enduring CSS.

您可以在Frain的书籍Enduring CSS中阅读有关此创新方法的所有详细信息。

结论 (Conclusion)

Writing maintainable and well organized CSS code has its challenges. In this article I’ve presented three methodologies that can help with the task. It’s by no means an exhaustive list and none of these approaches solves all the problems you might come across while working on a project.

编写可维护且组织良好CSS代码有其挑战。 在本文中,我介绍了可以帮助完成任务的三种方法。 这绝不是详尽的清单,并且这些方法都无法解决您在项目上可能遇到的所有问题。

Just try them out and see what works for you. You can also try using BEM and SMACSS together, or even work out your own methodology on the basis of the specific set of problems you set yourself to solve.

只需尝试一下,看看哪种对您有用。 您也可以尝试同时使用BEM和SMACSS ,甚至可以根据自己要解决的特定问题制定自己的方法。

What are your golden rules for writing organized, manageable CSS code? Do you think using a methodology for CSS architecture can ease the pain? Hit the comment box to let me know.

您编写有组织,可管理CSS代码的黄金法则是什么? 您认为使用CSS架构方法可以减轻痛苦吗? 点击评论框让我知道。

翻译自: https://www.sitepoint.com/tame-unruly-style-sheets-three-css-architecture-methodologies/

css样式表覆盖规则

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值