標籤:
原文[:Leveling up in CSS]
CSS seems easy at first. After all, it’s just styling, right?
But, give it time. Soon, CSS will show you the true depths of its complexity.
There are four things you can do to stay sane while using CSS at scale: use proper semantics, modularize, adopt a naming convention, and follow the single responsibility principle.
CSS起初看咋看很簡單,畢竟它只是樣式而已,對嗎?
但是,給點時間,很快CSS就要向你展示它的複雜性的真實深度。
在大規模使用CSS的時候有保持理性,有一下四個方面的事情可以去做: 適當的語義化, 模組化,採用一種命名規範,並遵循單一責任原則。
1、適當的語義化( Use proper semantics)
在HTML和CSS中有語義標記的概念。 語義意味著單詞和意義之間的關係。在HTML的環境中,意味著使用適當的標記,這有個經典的例子:
<!-- bad --><div class=”footer”></div><!-- good --><footer></footer>
Semantic HTML is pretty straightforward. On the other-hand, semantic CSS is much more abstract and subjective. Writing semantic CSS means choosing class names that convey structural meaning and function. Come up with class names that are easy to understand. Make sure they aren’t too specific. That way, you can reuse your classes.
語義的HTML相當的簡潔明了,另一方面,語義化的CSS相當的抽象並且主觀。 寫語義化的CSS時候意味著傳達結構上的意義和職責,提出一種便於理解的類名。確保它不是很具體,這樣你就可以重用你的類名。
為了列舉好的語義化的類名,這裡有CSS方法的一個簡單的例子:
<div class="stream"> <div class="streamItem"> <article class="postArticle"> <div class="postArticle-content"> <!-- content --> </div> </article> </div></div>
From the code, you can immediately discern structure, role, and meaning. The parent class is stream, a list of articles. The child class is streamItem, an actual article within the list. It’s clear how parent and child relate to one another. Furthermore, those classes are used on every page that features articles.
從上面的代碼中,能夠立即看清楚結構,角色,和意義。 父類是stream,是一個文章列表,子類是streamItem,是一個在列表之內的文章。父類和子類的關係很清楚。而且這樣的類可以在任何有文章的頁面中使用。
You should be able to read HTML and CSS like a book. It should tell a story. A story has characters and relationships between them. More semantic CSS will ultimately make your code more maintainable.
For further reading, check out What Makes for Semantic Class Names ,Naming CSS Stuff is Really Hard, and Semantics and Sensibility. For a longer read, see About HTML semantics and front-end architecture.
你可以想看書一樣來閱讀HTML和CSS,它應該告訴你一個故事,故事包含人物角色和他們之間的關係。好的語義化的CSS將從根本上讓你的代碼更好的維護。
進階閱讀,請挪步 怎樣語義化類名, 命名CSS這玩意真的好難,和 語義化和識別能力。較長的閱讀 ,請挪步 關於HTML的語義和前端構架。
2、模組化(Modularize)
In the age of component-based libraries like React, modularization is king. Think of components as composable modules created by deconstructing interfaces. Below is Product Hunt’s front page stream. As an exercise, let’s break the stream down into various components.
在像React這樣基於組件的庫的年代,模組化才是王道。
思考組件是由結構介面創造的可組合的模組,在產品的前端頁面流下,我們做一個練習,將這種流拆分成各種不同的組件。
Each colored outline represent a component. The stream has many stream items.
每一個顏色輪廓代表一個組件,這個流包含許多流項目。
<div class="stream"> <div class="streamItem"> <!-- product info --> </div></div>
Most components can be broken down into even smaller components.
大多數的組件可以被拆解成更小的組件,就像這樣:
Each stream item has a thumbnail and information about a featured product.
每一個流項目有關於特定產品的一個簡略圖和資訊
<!-- STREAM COMPONENT --><div class="stream"> <div class="streamItem"> <!-- POST COMPONENT --> <div class="post"> <img src="thumbnail.png" class="postThumbnail"/> <div class="content"> <!-- product info --> </div> </div> </div></div>
Because the stream component is independent of its children and vice versa, you can easily adjust or switch out the post class without making significant changes to the stream class.
流組件相對於它的孩子是獨立的,反之亦然,你可以很容易的調整或者更換出post的類而不用對流的class做多大的變化。
Thinking in components will help you make your decouple code. The more decoupled your code is, the lower the interdependence between your classes. This makes your code easier to modify and work with in the long run.
考慮組件可以協助使你的代碼解耦。 解耦的程度越高,你的類之間的互相依賴就越低。 這樣能夠使你的代碼容易修改並且長期運行。
When modularizing your CSS, start off by breaking your design down into component. You can do this with paper and pencil or in a program like Illustrator or Sketch. Identifying components will give you an idea of how to name your classes and how they relate to one another.
To read more about component driven CSS, check out CSS Architectures: Scalable and Modular Approaches, Writing Modular CSS with Sass, and Modularizing Your Front-End Code for Long Term Maintainability and Sanity.
當模組化CSS的時候,開始把你的設計拆分成組件,你可以用你的紙和筆或者使用像 Illustrator or Sketch 這樣的軟體,組件將會給你一個怎樣去命名你的類並且它們之間如何聯絡的一個思路。
更多關係組件化驅動CSS的文章請移步 CSS架構-可伸縮和模組化的方法, 用SASS寫模組化的CSS,為長期的維護和合理健全模組化你的前端代碼。
3、選擇一個好的命名規範(Choose a good naming convention)
There are dozens of CSS naming conventions out there. Some people swear by their choice of convention, claiming theirs is better than others. In truth, the best naming convention is different for each person. The best advice I ever received on this is: choose the naming convention that makes the most sense to you.
Here is a short list of some of the naming conventions people use:
- Object oriented CSS OOCSS
- Block element modifier (BEM)
- Scalable and modular architecture for CSS (SMACSS)
- Atomic
One of my favorite naming conventions is BEM. BEM stands for block, element, and modifier. Yandex, the Russian equivalent of Google, came up with it to issues they had with their CSS codebase at scale.
選擇一個靠譜的命名規範(Choose a good naming convention)
CSS的命名規範有一大把,有些人聲稱他們選擇的命名規範,聲稱他們的是比其他人的好。事實上,好的命名規範對每個人來說是不同的,我接收到的最好的建議是這樣:選擇對你自己最合理的的命名規範。
關於其他人使用的命名的約定這邊有一個列表:
- 物件導向的CSS OOCSS
- 區塊層級元素修飾 (BEM)
- CSS的可擴充和模組化構架 (SMACSS)
- 原子性
一種我最喜歡的命名規範是BEM,BEM 代表塊,元素和修飾。 Yandex,俄羅斯人的Google,他們在處理自己那種規模的程式碼程式庫時候想出來的解決方案。
BEM is one of the simplest — yet strictest — of the naming conventions.
BEM是一種簡單又嚴格的命名規範。
.block {}.block__element {}.block--modifier {}
Blocks represent higher level classes. Elements are children of blocks. And modifiers represent different states.
block代表高層次的類,元素是類的子項目,並且修飾器代表了不同的狀態。
<div class="search"> <input type="search__btn search__btn--active" /></div>
In the example above, the class search is the block and search button is its element. If we want to modify the state of the button, we can add a modifier like active .
One thing to remember about naming conventions is that regardless of which CSS naming convention you prefer, you will often times inherit or work on codebases with different standards. Be open to learning new standards and alternative ways of thinking about CSS.
You can read more about BEM in Getting your head ’round BEM syntax , BEM 101 , and Intro to BEM . For general reading about different conventions, check outOOCSS, ACSS, BEM, SMACSS: what are they? What should I use?
在這個例子中,search類是個塊,搜尋按鈕是元素,如果我們想修改按鈕的狀態,可以添加一個修改器像active.
忽略你所熟悉的CSS命名規範,你會經常繼承或者在不同的程式碼程式庫的標準下工作。以開放的心態去學習新的標準和替代的方式去思考CSS.
關於BEM的更多的閱讀 開始瞭解BEM的文法,BEM101, BEM簡介。關於不同的約定一般閱讀, OOCSS,ACSS,BEM,SMACSS 他們是什嗎? 我應該用哪個?
4、 遵循單一責任的原則 (Follow the single responsibility principle )
The single responsibility principles states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class.
Within the context of CSS, the single responsibility principles means that pieces of code, classes and modules should do only one thing. When applied to CSS file organization, this means that self-contained components like carousels and navigation bars should have their own CSS file.
單一責任原則指出每一個模組或者類都應該對一個支援軟體功能的一個單一部分負責,這種責任應該完全被封裝在類中。在CSS的上下文環境中,單一責任原則意味著一個程式碼片段,一個類,或者一個模組應該做一件事情。 當應用於CSS的組織的時候,這代表獨立的組件,像導覽列和輪播應該有他們自己的CSS檔案,就像下邊這樣的:
Another common pattern in file organization is grouping files by functionality. For example, in the snippet above, all the files related to the carousel component are grouped together. Adopting this approach makes finding files much easier.
In addition to separating component styles, it’s good to separate global style using the single responsibility principle.
另外一種組織檔案的普通的模式是將檔案按照功能分組。舉個例子,在上面的程式碼片段中,所以的和輪播相關的檔案組織在一起。 採用這樣的方法使得尋找檔案變得相當簡單。
另外對於分離組件樣式,將全域的樣式按照單一責任原則抽離開是不錯的。
In the example, each style concern is separated into its own file. This way, if you want to update your colors, you know exactly where to look.
Regardless of which file organization convention you use, let the single responsibility principle help guide your decisions. If one file starts getting bloated, consider partitioning it out based on what makes logical sense.
For more on file structures and CSS architecture, read Aesthetic Sass 1: Architecture and Style Organization and Scalable and Maintainable CSS Architecture.
When the single responsibility principle is applied to individual CSS classes, it means that each class should have only one function. In other words, separate out styles into different classes based on concerns. Here is a classic example:
在這例子中,每種設計的樣式被分離在自己的檔案中,這樣,如果你想要更新你的顏色,應該很明確在哪裡找。
不管你用哪一種檔案組織約定,湯單一責任原則協助你指導你的決定,如果一個檔案開始變得臃腫,考慮從基於邏輯層面劃分這個檔案。
更多的關於檔案結構和CSS架構,閱讀 審美SASS, 架構和組織CSS和可伸縮以及可維護的架構風格。
當單一責任原則被CSS的類所採用,這意味著每個類必須只有一個功能,換句話說,基於關係將樣式劃分成為不同的類,這裡有個經典的案例:
.splash { background: #f2f2f2; color: #fffff; margin: 20px; padding: 30px; border-radius: 4px; position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
In the example above, we are mixing concerns. The splash class not only contains presentation and styling logic for itself, but for its children as well. To remedy this, we can split the code into two separate classes.
在上邊的例子中,我們混合了不同的點,這個類不僅包含展現和自己的樣式邏輯,還包含自己自元素的,為了拯救它,我們可以將樣式代碼分開在兩個單獨的類中。
.splash { position: absolute; top: 0; right: 0; bottom: 0; left: 0;}.splash__content { background: #f2f2f2; color: #fffff; padding: 30px; border-radius: 4px;}
Now we have a splash and splash content. We can use splash as a generic full-bleed class that takes any child. All of the concerns of the child, in this case the splash content, are decoupled from the parent.
現在我們有slash和splash__content 我們可以使用splash作為一個普通的可以容納任何子類的類,所有與子類有關的特性,在這個例子中與父類完全解耦。
You can read more about applying the single responsibility approach to styling and classes in The single responsibility principle applied to CSS and Single Responsibility.
可以閱讀更多關於採用單一責任的方法書寫樣式和類的文章 The single responsibility principle applied to CSS and Single Responsibility.
簡單超越複雜(Simplicity over complexity)
Ask any good front-end developer or CSS architect and they will tell you that they’ve never been fully satisfied with their code. Writing good CSS is an iterative process. Start simple, follow basic CSS conventions and style guides, and iterate from there.
If you enjoyed this article, you might like the article I wrote that teaches you five important characteristics of good design through k-pop.
I would love to know how you approach CSS. What is your favorite naming convention? How do you organize your code? Feel free to leave a note or Tweet to me.
去問任何好的前端開發人員或者CSS架構師,他們會告訴你他們從來沒有真正的對自己的代碼完全滿意過。 編寫好的CSS是一個反覆迭代的過程,從簡單的開始,遵循基本的CSS約定和風格指南,並從那裡開始迭代。
CSS進階( Leveling up in CSS)