Skip to main content

CSS 样式书写

在 CSS 中,有一组推荐的书写顺序,以确保 CSS 样式尽可能明确,方便阅读和维护:

  1. 定位
  2. 显示/隐藏
  3. box 模型
  4. 浮动和定位
  5. 文本属性
  6. 背景
  7. 边框
  8. 高级

其中,把定位放在首位,原因是它可能改变元素的大小,而其他属性都可由元素的大小和位置来定。

书写顺序

定位 Position 和布局 Layout

  • position
  • top/bottom/left/right
  • z-index
  • float/clear
  • flexbox
    • flex-direction
    • justify-content
    • align-items
    • 等等...

展示 Display 和可见 Visibility

  • display
  • opacity
  • visibility

盒子模型 Box Model

  • margin
  • box-shadow
  • border
  • border-radius
  • width/height
  • padding

背景设置 Background

  • background

字体 Font 和文本 Text

  • font-family/font-size/font-weight/font-style
  • line-height
  • text-align/text-transform
  • color

其他属性 Other Property

  • overflow
  • clip
  • cursor
  • transform
  • animation、transition
  • white-space

CSS 样式不生效技巧

  • 为何有时候编写的 CSS 属性不好使,有可能是因为

    • 选择器的优先级太低
    • 选择器没选中对应的元素
  • CSS 属性的使用形式不对

    • 元素不支持CSS 属性,比如 span 默认是不支持 widthheight
    • 浏览器不支持CSS 属性,比如旧版本的浏览器不支持一些 css module3 的某些属性
    • 被同类型的 CSS 属性覆盖,比如 font 覆盖 font-size
  • 建议:充分利用浏览器的开发者工具进行调试 (增加、修改样式)、查错

推荐文章