CSS 规则的优先级顺序

  • Order of Precedence for CSS Rules;

The location of the styles and rules is one factor in the order of precedence. Specific rules take precedent over more general rules. Also, the rules toward the end of a style sheet take precedence over the front rules.

  • CSS cascade W3C specification;
    stackoverflow: The order in which the classes appear in the html element does not matter, what counts is the order in which the blocks appear in the style sheet.
    样式表有三种laidefault, author, user style
三种来源(origin)的优先顺序
  • user style sheet 一般用户不会使用,并且也主要是用来规范浏览器厂商渲染使用的;
    Sort according to importance (normal or important) and origin (author, user, or user agent):
    1. User Agent
    2. User Normal
    3. Author Normal
    4. Author Important
    5. User Important
  • 在实际应用中,用户自定义的样式表已经脱离我们的控制,我们要考虑的就是:
    ☆ User Agent(浏览器)
    ☆ Author Normal (网站文件)
    ☆ Author Important
    有一个我们熟知的基本逻辑,即网站通常会写一个基本样式文件,以覆盖浏览器默认样式;
  • Default style sheets are supplied by the browser vendor.
    浏览器默认样式;
    user agent 用户代理,也就是浏览器,比如 IE、Chrome、...,每个浏览器有自己的默认样式;
  • Author style sheets are supplied by the author of a webpage.
    网站样式;Author 就是网站的制作者;
  • User style sheets are supplied by the user of the browser.
    用户自定义样式;User 是网站的阅读者,可以定义自己的样式,比如字体加大、改个颜色什么的,主要是满足 Web accessibility(网络无障碍)要求,以实现失能人士可以顺利获取信息的一般权利;
    userstyles.org 提供了浏览器插件,可以管理使用 user style,比如:Stylish for Chrome;
关于 Normal & !important style
  • Normal 样式是按照从上到下的方法处理的;
    假定先定义了 background-color:#00ff00; 然后又定义了 background-color:#000000;
    渲染结果:对同一个元素,黑色背景是胜出的;
  • Important 样式会复写 Normal 样式;
    同样的例子,先定义 background-color:#00ff00 !important; 然后又定义了 background-color:#000000;
    渲染结果:尽管黑色背景定义在后,但是最后是黄色胜出;
  • 使用 !important 或者加一个 inline style,应当慎重使用;

你可能感兴趣的:(CSS 规则的优先级顺序)