bem css_如何使用ITCSS和BEM解决大规模CSS瓶颈

news/2024/7/5 12:37:28

bem css

介绍 (Introduction)

On frontend codebase projects, requirements and sometimes scopes can change frequently. When requirements change and you adjust the stylesheet or extend the styles of a selector in a particular page, such changes often affects other views that share similar styles.

在前端代码库项目中,需求和范围有时可能会经常更改。 当需求发生变化并且您在特定页面中调整样式表或扩展选择器的样式时,此类更改通常会影响共享相似样式的其他视图。

This may lead to many hours of specificity wars while trying to override styles. That happens because the project was not structured in a proper way that would ensure that changes to the stylesheets would not have a negative impact on the entire project. In this tutorial, you’ll see how to combine Block Element Modifier (BEM) CSS with Inverted Triangle CSS (ITCSS) to avoid problems.

在尝试覆盖样式时,这可能会导致数小时的特异性冲突。 发生这种情况是因为项目的结构不正确,无法确保样式表的更改不会对整个项目产生负面影响。 在本教程中,您将看到如何结合使用块元素修饰符(BEM)CSS和倒三角形CSS(ITCSS)来避免问题。

使用CSS时遇到的常见困难 (Common Difficulties Faced while Working with CSS)

CSS as a language has a few issues that make managing it a bit difficult for developers.

CSS作为一种语言存在一些问题,这使得开发人员对其进行管理有些困难。

  • It is declarative, meaning that it does not have a control flow that tells you the state of a project.

    它是声明性的,这意味着它没有告诉您项目状态的控制流。
  • Everything exists on the global scope, making style collisions possible.

    一切都存在于全局范围内,从而使样式冲突成为可能。
  • There is also the issue of specificity, which determines the style that is being applied to a particular selector.

    还有一个特殊性问题,它决定了要应用于特定选择器的样式。

These issues become much more evident when a project grows and more developers are working in the same codebase. If proper structures are not put in place, then changes to the stylesheets tend to become unpredictable.

当项目增长且更多开发人员在同一代码库中工作时,这些问题变得更加明显。 如果没有适当的结构,则样式表的更改往往变得不可预测。

In order to properly structure CSS in a way that would help us avoid these issues, Harry Roberts created “Inverted Triangle CSS (ITCSS)”. It is a methodology that can help us structure CSS in such a way that they behave in a more predictable manner. It was designed to help developers working in large scale projects to better organize and manage their CSS.

为了以能够帮助我们避免这些问题的方式正确构造CSS, Harry Roberts创建了“倒三角CSS(ITCSS)”。 它是一种可以帮助我们以更可预测的方式构造CSS的方法。 它旨在帮助从事大型项目的开发人员更好地组织和管理CSS。

According to Harry, ITCSS is a collection of principles and metrics by which developers should group and order their CSS to keep it scalable, terse, logical, and manageable. It’s a methodology that involves visualizing a CSS project as a layered, upside-down triangle. This hierarchical shape represents a model that will order CSS by metrics defined by the design of the language with better scalability and maintainability than we’d get if we were to write CSS around how a person thinks.

根据Harry的说法,ITCSS是一组原则和指标,开发人员应根据这些原则和指标对CSS进行分组和排序,以使其具有可扩展性,简洁性,逻辑性和可管理性。 这种方法涉及将CSS项目可视化为分层的上下三角形。 这种分层的形状表示一个模型,该模型将按照语言设计所定义的指标对CSS进行排序,其伸缩性和可维护性要比我们围绕人的想法编写CSS时得到的更好。

ITCSS is also flexible and can be used with or without preprocessors. It is compatible with other CSS methodologies like BEM, SMACSS or OOCSS. As we progress in this tutorial, I will show you how you can use ITCSS with BEM.

ITCSS也是灵活的,可以与或不与预处理器一起使用。 它与其他CSS方法如BEM,SMACSS或OOCSS兼容。 随着本教程的进展,我将向您展示如何将ITCSS与BEM一起使用。

ITCSS的基本原理 (Basic Principles of ITCSS)

CSS中没有ID (No IDs in CSS)

IDs have high selector specificity and this can make it difficult to override styles. To override an ID, we add more IDs or use !important, which can begin specificity wars in your stylesheets. Overriding and extending styles shouldn’t be difficult so as to make your CSS maintainable and pleasant to work with.

ID具有较高的选择器特异性,这可能会使覆盖样式变得困难。 要覆盖ID,我们可以添加更多ID或使用!important ,这可以在样式表中开始特殊性战争。 覆盖和扩展样式应该不难,以使您CSS易于维护和使用。

组件UI模式 (Component UI Pattern)

A component is a collection of reusable markups usually with some logic and styling. Components are self-contained and they serve as building blocks of modern frontend technologies: React, Angular, Vue, Ember, etc. ITCSS favors componentized UI architecture over pages.

组件是通常具有某种逻辑和样式的可重用标记的集合。 组件是独立的,它们是现代前端技术的构建块:React,Angular,Vue,Ember等。ITCSS偏爱页面化的组件化UI架构。

基于类的架构 (Class-Based Architecture)

A good CSS architecture is one that is reusable and flexible. ITCSS favors the use of classes since they can be used multiple times on the same page and multiple classes can be placed in a particular element. Classes also make HTML easier to read.

好CSS架构是可重用且灵活的。 ITCSS赞成使用类,因为它们可以在同一页面上多次使用,并且可以将多个类放在一个特定的元素中。 类还使HTML更易于阅读。

ITCSS的关键指标 (Key metrics of ITCSS)

ITCSS orders your project using three key metrics.

ITCSS使用三个关键指标对项目进行排序。

通用样式到显式样式 (Generic Styles to Explicit Styles)

Start out with generic, high-level and far-reaching selectors and then gradually proceed to explicit and more specific selectors. You can start with browser reset rules and then proceed to element selectors and right through to explicit rules such as btn-primary.

从通用,高级且影响深远的选择器开始,然后逐步进行到显式和更具体的选择器。 您可以从浏览器重置规则开始,然后继续进行元素选择器,然后直通至明确的规则,例如btn-primary

从低特异性到高特异性 (Low Specificity to High Specificity)

Every CSS rule has a specificity weight which means that it could be more or less important than the others or equally as important. This weight defines which properties will be applied to an element when there are conflicting rules. Keeping less specific rules at the top and high specific rules under them ensure that your styles cascade properly to avoid conflicts and specificity wars.

每个CSS规则都有特定的权重,这意味着它可能比其他规则或多或少重要,或者同等重要。 此权重定义在存在冲突规则时将哪些属性应用于元素。 在顶部保留较少特定的规则,在其下方保留较高的特定规则,可确保您的样式正确地级联以避免冲突和特定性冲突。

远程到本地化 (Far-Reaching to Localised)

At the start of a project, CSS rules affect a lot of the DOM, but as we progress through the project the rules affect less of the DOM and become more specific to components. We might start by wiping the margins and paddings off everything. Next, we might style every type of element, then narrow it down to every type of element with a certain class applied to it, and so on. It is this gradual narrowing down of reach that gives us the triangle shape.

在项目开始时,CSS规则会影响很多DOM,但是随着我们在项目中的进行,这些规则对DOM的影响会越来越小,并且变得更加针对组件。 我们可能首先要擦除所有内容的marginspaddings 。 接下来,我们可以为每种类型的元素设置样式,然后将其缩小为每种类型的元素,并应用特定的类,依此类推。 正是这种逐渐缩小的范围使我们形成了三角形。

好处 (Benefits)

Following these three key metrics has a lot of benefits, to mention a few:

遵循这三个关键指标有很多好处,仅举几例:

  • Global and far-reaching styles are shared more effectively and efficiently.

    全球和深远的风格可以更有效地共享。

  • The probability of specificity wars is reduced since CSS is written in a logical and progressive order in terms of specificity.

    由于CSS在特异性方面是按逻辑和渐进顺序编写的,因此降低了特异性冲突的可能性。

  • CSS becomes more extensible and redundant styles are avoided leading to lesser file sizes, and latency.

    CSS变得更具扩展性,避免了多余的样式,从而减少了文件大小和延迟。

  • We spend very little time undoing things because our cascade and specificity are all pointing in the same direction

    我们花很少的时间做事情,因为我们的级联和特异性都指向同一个方向

ITCSS层 (ITCSS Layers)

Breaking our CSS into layers helps us stick to the above mentioned metrics. Each layer is added in a location that aligns with the metrics. Each layer is usually a logical progression of the previous layer. As we progress through the layers, explicitness and specificity increases and the reach of the selectors are narrowed.

将CSS分成几层有助于我们遵守上述指标。 将每个层添加到与指标对齐的位置。 每层通常是前一层的逻辑顺序。 随着我们逐步深入各层,明确性和特异性增加,选择器的范围缩小。

This means that CSS becomes easier to scale since we are writing it in an order that only adds to what was previously written. It also means that everything has its own predictable location to live, which makes it easier to find and add styles.

这意味着CSS变得更易于扩展,因为我们以仅增加先前编写内容的顺序编写它。 这也意味着一切都有其可预测的居住位置,这使得查找和添加样式变得更加容易。

ITCSS has seven layers which we would take a closer look at here:

ITCSS分为七个层,我们将在这里进行仔细研究:

设定值 (Settings)

This is the starting point when using CSS preprocessors. It contains global variables that can be accessed from anywhere within your CSS project. Examples of global settings are font sizes and colour definitions.

这是使用CSS预处理程序的起点。 它包含可以从CSS项目中任何位置访问的全局变量。 全局设置的示例包括字体大小和颜色定义。

工具类 (Tools)

This contains global functions and mixins and it comes after the settings since the mixins and functions might need access to global settings. This layer is the second layer if you are using preprocessors. Examples are font-size mixins px-to-rem mixins, etc. It is important to avoid writing actual styles in the first two layers.

它包含全局函数和混合函数,它位于设置之后,因为混合函数和功能可能需要访问全局设置。 如果使用预处理器,则此层为第二层。 例如, font-size mixins px-to-rem mixins等。避免在前两层中编写实际样式非常重要。

泛型 (Generic)

This is the point where actual CSS is written and it is also the starting point if you are not using a preprocessor. It contains styles such as CSS reset roles, global box-sizing rules, and CSS normalising rules. The styles here affect much of the DOM.

这是编写实际CSS的地方,也是不使用预处理器的起点。 它包含样式,例如CSS重置角色,全局框大小规则和CSS规范化规则。 这里的样式会影响很多DOM。

元件 (Element)

This layer contains element selector styles. It contains styles for bare and un-classed HTML elements. Styles for form, heading, img, links and table elements also come in here. Styles here are still very low-specificity but affects slightly less of the DOM.

该层包含元素选择器样式。 它包含裸露和未分类HTML元素的样式。 formheadingimglinkstable元素的样式也都在这里。 这里的样式仍然是很特殊的,但是对DOM的影响却很小。

对象 (Objects)

This is the first layer with class-based selector. It contains styles for non-cosmetic objects such as containers, wrappers and layout systems. This layer affects less of the DOM than the last layer, has a higher specificity, and is slightly more explicit given that we are now targeting specific sections of the DOM with classes.

这是具有基于类的选择器的第一层。 它包含非化妆品对象的样式,例如容器,包装器和布局系统。 该层对DOM的影响比上一层要小,具有更高的特异性,并且由于我们现在使用类来定位DOM的特定部分,因此该层的含义更加明确。

组件 (Components)

This layer holds the style for each component in your project. It’s more explicit than the previous layer because we are now styling visible UI elements. In component based frameworks like Angular, Vue or React, this is the layer where you import your styling for each component if you don’t include them directly in your component.

该层包含项目中每个组件的样式。 它比上一层更加明确,因为我们现在正在设计可见的UI元素。 在基于组件的框架(例如Angular,Vue或React)中,如果不将其直接包含在组件中,则可以在该层中导入每个组件的样式。

特朗普 (Trumps)

This layer beats other layers. This is where utility and helper styles are defined. It is specificity heavy, can override previous styles and is the tip of the triangle. Most of the styles here contain the !important flag.

该层击败其他层。 这是定义实用程序和帮助程序样式的地方。 它的特异性很强,可以覆盖以前的样式,是三角形的尖端。 这里的大多数样式都包含!important标志。

结果 (The result)

When all the layers are combined together, it could look like this.

当所有图层组合在一起时,看起来可能像这样。

// main.scss
@import "settings.fontsize";
@import "settings.colors";

@import "tools.functions";
@import "tools.mixins";

@import "generic.reset";
@import "generic.normalize";

@import "elements.forms";
@import "elements.table";

@import "objects.contianer";
@import "objects.grid";

@import "components.site-nav";
@import "components.buttons";
@import "components.carousel";
@import "trumps.clearfix";
@import "trumps.utilities";

在ITCSS中使用BEM (Using BEM with ITCSS)

Block Element Modifier(BEM) is a methodology for naming CSS styles. According to Getbem, BEM is a highly useful, powerful, and simple naming convention that makes your front-end code easier to read and understand, easier to work with, easier to scale, more robust and explicit, and a lot more strict.

块元素修饰符(BEM)是命名CSS样式的方法。 根据Getbem的说法 ,BEM是一种非常有用,功能强大且简单的命名约定,它使您的前端代码更易于阅读和理解,易于使用,易于扩展,更健壮和明确,并且更加严格。

BEM is particularly useful for the six and seventh layer of ITCSS where class-based selectors are heavily used. Following BEM would ensure that classes are properly named for better readability.

对于大量使用基于类的选择器的ITCSS的第六和第七层,BEM特别有用。 遵循BEM将确保正确命名类,以提高可读性。

举例说明BEM方法论 (Exemplifying the BEM Methodology)

B (Block) A block is a top-level node, the highest level abstraction of a component. It is a standalone entity or a component, on a web page.

B(块)块是顶层节点,是组件的最高层抽象。 它是网页上的独立实体或组件。

Example:

例:

.btn {
  rules
}

E (Element) Elements are children of a block. They have no standalone meaning and are semantically tied to a block. Elements are prefixed with their block name and a double underscore.

E(元素)元素是块的子元素。 它们没有独立的含义,并且在语义上与块相关。 元素以其块名和双下划线为前缀。

Example:

例:

.btn__text {
  rules
}

.btn__icon {
  rules
}

M (Modifiers) Modifiers are used to change the appearance of a block or an element. They provide us with a way of creating variations of blocks and elements rules.

M(修饰符)修饰符用于更改块或元素的外观。 它们为我们提供了创建块和元素规则的变体的方法。

.btn--lg {
  rules
}

.btn__text--light {
  rules
}

.btn__icon--right {
  rules
}

结论 (Conclusion)

When there is a need for change in your codebase, you don’t want to spend time overriding styles and fighting specificity wars. The inverted triangle architecture makes sure that there is no war by helping you visualize the state of your entire codebase in simple terms.

当需要在代码库中进行更改时,您不想花费时间来覆盖样式和对抗特定性战争。 倒三角结构通过帮助您以简单的方式可视化整个代码库的状态来确保不打架。

Following its principles helps create a system that is approachable, predictable, guessable, rule based, prone to smaller file sizes, and geared toward scalability and growth.

遵循其原理有助于创建一个易于访问,可预测,可猜测,基于规则的系统,易于生成较小的文件,并具有可扩展性和可扩展性。

If you’re working on a front-end project that makes heavy use of CSS, i would recommend using ITCSS with BEM so as to make your code easier to read and understand. This will not only ensure good maintenance of the code but also promote empathy for incoming developers.

如果您正在忙于大量使用CSS的前端项目,我建议将ITCSS与BEM一起使用,以使您的代码更易于阅读和理解。 这不仅可以确保代码的良好维护,还可以促进新开发人员的同理心。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-solve-large-scale-css-bottlenecks-with-itcss-and-bem

bem css


http://www.niftyadmin.cn/n/3649650.html

相关文章

Java基础---多态、抽象类、接口

2015-4-4 一、多态 1、定义:某一个事物,在不同时刻表现出来的不同状态。 2、多态的前提与体现: (1)要有继承关系; (2)要进行方法的重写; (3)要父…

移动开发:ionic框架的Android开发环境搭建

一、解决Eclipse与Android Studio的SDK冲突 Eclipse与Android Studio不能共用一套Android SDK,Android Studio会改变SDK的结构,eclipse不能正常使用Android SDK。但是我这个学期的两个课程都与Android开发有关。而且两个课程使用的开发工具都不一样。一边…

[流媒体]实例解析MMS流媒体协议,下载LiveMediaVideo[2][修正版本]

编写者日期关键词郑昀ultrapower2005-10-17mms streaming protocol ethereal 协议分析 流媒体为了改造mimms,我分析了SDP和流媒体服务器的来往包,看看我和他的实现到底存在哪些差异。如果你也开发流媒体下载应用,希望这个分析对你理解 “Micr…

react集成钉钉api_如何将Google Maps API集成到React应用程序中

react集成钉钉api介绍 (Introduction) This tutorial aims at integrating the google maps API to your React components and enabling you to display maps on your website. 本教程旨在将google maps API集成到您的React组件中,并使您能够在网站上显示地图。 先…

Android项目实战系列—基于博学谷(四)我的模块(上)

由于这个模块内容较多,篇幅较长,请耐心阅读。 “我”的模块分为四个部分 我的界面 设置界面 修改密码界面 设置密保和找回密码 一、“我”的界面 1、底部导航栏 (1)、导入界面图片 将底部导航栏所需图片main_course_icon.png、main_course…

[流媒体]实例解析MMS流媒体协议,下载LiveMediaVideo[1]

[流媒体]按照MMS协议和MS Media Server交互下载实时交通录像的包分析---实例解析MMS流媒体协议,下载LiveMediaVideo编写者日期关键词郑昀ultrapower2005-10-17mms streaming protocol ethereal 协议分析 流媒体通过mms://220.194.63.17/cebeijing8,我们可…

如何在Visual Studio Code中调试Angular CLI应用程序

介绍 (Introduction) In this post, you’ll create an Angular CLI application, then add configuration to debug it in Visual Studio Code. 在本文中,您将创建一个Angular CLI应用程序,然后添加配置以在Visual Studio Code中对其进行调试。 TLDR-对…