前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >前端开发规范CSS

前端开发规范CSS

作者头像
PM吃瓜
发布2019-08-12 14:47:48
5270
发布2019-08-12 14:47:48
举报

代码组织

以组件为单位组织代码段;

  • 如果使用了多个 CSS 文件,将其按照组件而非页面的形式分拆,因为页面会被重组,而组件只会被移动;

Class 和 ID

使用语义化、通用的命名方式;

使用连字符 - 作为 ID、Class 名称界定符,不要驼峰命名法和下划线;

避免选择器嵌套层级过多,尽量少于 3 级;

避免选择器和 Class、ID 叠加使用;

/* Not recommended */
.red {}
.box_green {}
.page .header .login #username input {}
ul#example {}
/* Recommended */
#nav {}
.box-video {}
#username input {}
#example {}
声明顺序相关属性应为一组,推荐的样式编写顺序
  • Positioning
  • Box model
  • Typographic
  • Visual

由于定位(positioning)可以从正常的文档流中移除元素,并且还能覆盖盒模型(box model)相关的样式,因此排在首位。盒模型决定了组件的尺寸和位置,因此排在第二位。

.declaration-order {
  /* Positioning */
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100;

  /* Box model */
  display: block;
  box-sizing: border-box;
  width: 100px;
  height: 100px;
  padding: 10px;
  border: 1px solid #e5e5e5;
  border-radius: 3px;
  margin: 10px;
  float: right;
  overflow: hidden;

  /* Typographic */
  font: normal 13px "Helvetica Neue", sans-serif;
  line-height: 1.5;
  text-align: center;

  /* Visual */
  background-color: #f5f5f5;
  color: #fff;
  opacity: .8;
  /* Other */
  cursor: pointer;

}

任何超过 1000 行的 CSS 代码,你都曾经历过这样的体验:

这个 class 到底是什么意思呢?

这个 class 在哪里被使用呢?

如果我创建一个 xxoo class,会造成冲突吗?

Dash prefixes (中划线前缀)

为什么使用中划线作为变体的前缀?

  • 它可以避免歧义与 Elements
  • CSS class 仅能以单词和 _- 开头
  • 中划线比下划线更容易输出

Avoid positioning properties (避免定位属性)

Components 应该在不同的上下文中都可以复用,所以应避免设置以下属性:

  • Positioning (position, top, left, right, bottom)
  • Floats (float, clear)
  • Margins (margin)
  • Dimensions (width, height) *

Fixed dimensions (固定尺寸)

头像和 logos 这些元素应该设置固定尺寸(宽度,高度...)。

Define positioning in parents (在父元素中设置定位)

倘若你需要为组件设置定位,应将在组件的上下文(父元素)中进行处理,比如以下例子中,将 widthsfloats 应用在 list component(.article-list) 当中,而不是 component(.article-card) 自身。

.article-list {
    & {
      @include clearfix;
    }

    > .article-card {
      width: 33.3%;
      float: left;
    }
  }

  .article-card {
    & { /* ... */ }
    > .image { /* ... */ }
    > .title { /* ... */ }
    > .category { /* ... */ }
  }

Summary (总结)

  • Components 的角度思考,以两个单词命名(.screenshot-image
  • Components 中的 Elements,以一个单词命名(.blog-post .title
  • Variants,以中划线-作为前缀(.shop-banner.-with-icon
  • Components 可以互相嵌套
  • 记住,你可以通过继承让事情变得更简单
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-04-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Tech爬虫 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 代码组织
  • Class 和 ID
    • Dash prefixes (中划线前缀)
      • Avoid positioning properties (避免定位属性)
        • Fixed dimensions (固定尺寸)
          • Define positioning in parents (在父元素中设置定位)
          • Summary (总结)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档