Skip to content

Instantly share code, notes, and snippets.

@democ
Created April 1, 2014 00:45
Show Gist options
  • Save democ/9905591 to your computer and use it in GitHub Desktop.
Save democ/9905591 to your computer and use it in GitHub Desktop.

I believe the goals of good CSS architecture shouldn’t be that different from the goals of all good software development. I want my CSS to be predictable, reusable, maintainable, and scalable.

Predictable

Reusable

CSS需要足够的抽象和解耦从而能够很快利用存在的部分建立新的components.而不需要从头开始写那些你已经写过的模式和已解决的问题来完成这项任务.

Maintainable

When new components and features need to be added, updated or rearranged on your site, doing so shouldn’t require refactoring existing CSS. Adding component X to the page shouldn’t break component Y by its mere presence.

Scalable

Scalable CSS means it can be easily managed by a single person or a large engineering team. It also means your site’s CSS architecture is easily approachable without requiring an enormous learning curve. Just because you’re the only developer touching the CSS today doesn’t mean that will always be the case.

Avoding Common Bad Practices

避免根据父级元素调整组件样式

You will learn how to modify components without relyig on parent selectors.

  // 不好的代码
  .widget {}
  #sidebar .widget {}
  body.homepage .widget {}

一开始这看起来是很合理的代码,但是让我们来分写一下上面代码代码.

(1) 示例中的代码不可预测
编写.widget组件的人想让是想给这个组件一个固定的样子.可是当他把.widget组件放在sidebar或者是.homepage中时,.widget组件的样子和预想中的不一样了.然而所有的代码都是一样的.

(2) 难以重用
当我在其他页面需要一个和homepage或者是sidebar中看起来一样的.widget时,就必须加入新的选择器规则.

(3) 难以维护
如果.widget需要重新设计的时候,就必须去CSS中更改很多地方.

避免复杂的选择器

选择器越复杂,则越依赖HMLT结构,与HTML耦合更紧密.

避免太通用的class名字

创建可重用的组件时,最常做的是scope the component's sub-elements inside the components's class name(翻译无力).

  //不好的代码
  <div class="widget">
    <h3 class="title">...</h3>
    <div class="contents">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit.
      In condimentum justo et est dapibus sit amet euismod ligula ornare.
      Vivamus elementum accumsan dignissim.
      <button class="action">Click Me!</button>
    </div>
  </div>
  .widget {}
  .widget .title {}
  .widget .contents {}
  .widget .action {}

(1) 代码不可预测
On a large project it’s very likely that a class name like .title would get used in another context or even by itself. If that happened, the widget’s title would suddenly look very different than intended.

避免让一条规则做的太多

  //不好的代码
  .widget {
    position: absolute;
    top: 20px;
    left: 20px;
    background-color: red;
    font-size: 1.5em;
    text-transform: uppercase;
  }

(1) 难以重用 假设接下来需要在不同的位置使用这个组件. 以上的代码就不管用了. 你让在选择器中定义了太多方面的规则: 1)look and feel; 2)layout and position.这里样式是可以重用的,但是布局和位置无法重用.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment