Home  >  Article  >  Web Front-end  >  css 优先级_html/css_WEB-ITnose

css 优先级_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:24:43955browse

css优先级
  很早以前就知道对同一个元素设置样式时应用样式的优先级是
  内联样式>页内样式>大于外联样式
  id选择器>class选择器>标签选择器
  很简单 一笔带过
  但事实上 如果是做前端开发的 还需要更了解详细些
  1. !important 是拥有绝对最高优先级的 (设置此值后无论id选择器还是内联样式都无法撼动它)
      .set_size{width:inherit !important;}
  2.如果不小心在写样式时将外联样式放在了自己单独指定的页内样式前面 外联样式优先级将高于页内样式 这主要是引入css库时需要注意的
  但此时内联样式的优先级仍高于外联样式的类选择器优先级
  页内样式的id选择器仍高于外联样式的类选择器
  此时 内联>外联id>页内id>外联类选择>页内类选择
  3.*通配符选择器,会选择页面所有的元素 相当于对页面的每一个元素都应用了一次此样式
  很强大,但不好  正确的使用姿势应该是与后代选择器配合使用 如
  .foot_thin *{color:blue;}
 
  正常情况下
 
 
  内联>页内id>外部id>页内类选择>外部类选择......

  后代选择器优先级高于类选择器
  p span{color:red;}
  子选择器优先级和后代选择器相等(在写法相同的情况下)
  p > span{color:blue;}
  同一css文件中此时是red还是blue 取决于谁写在谁的上一行 在后面的优先级不会更高 但浏览器后渲染 定下来了后面的样式
  优先级会叠加
  p.is > span{color:black;} 此时优先级会加上类选择器的优先级
 
  id>后代选择

  256个类选择器干掉一个id选择器
  http://www.zhangxinxu.com/study/201208/256-class-fire-an-id.html

  绝不忘记目的( never forgotten purpose )
  需要了解css优先级是因为我们需要准确的精简冗余低的便利的可重用的高效的选择元素 从而应用样式 构建一个棒棒的web站点(当然性能优化这方面的东西很大重头戏在后台)
  但是这不代表运行在前端的东西就不用考虑性能 完全不去考虑前端的性能,这合适吗?
  答案显而易见

  效率从高到低为
    id选择器(#myid)
    类选择器(.myclassname)
    标签选择器(div,h1,p)
    相邻选择器(h1+p)
    子选择器(ul     后代选择器(li a)
    通配符选择器(*)
    属性选择器(a[rel="external"])
    伪类选择器(a:hover,li:nth-child)
  但写css的前端,大家基本不会业余到用id选择器
  而伪类是有必要的而常用的

  更多up可读
  http://stevesouders.com/
  http://www.tuicool.com/articles/INbuiq
  http://csswizardry.com/2011/09/writing-efficient-css-selectors/ or http://www.w3cplus.com/css/css-selector-performance
  http://www.jianshu.com/p/268c7f3dd7a6

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn