04.选择器的权重.html 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. #box {
  10. background-color: blue;
  11. }
  12. div#box {
  13. background-color: green;
  14. }
  15. div {
  16. background-color: yellow !important;
  17. }
  18. .red {
  19. background-color: red;
  20. }
  21. .d1{
  22. background-color: purple;
  23. }
  24. /* div,p,span {
  25. background-color: yellowgreen;
  26. } */
  27. /*
  28. 样式的冲突
  29. -当我们通过不同的选择器,选中相同的元素,并且为相同的样式设置不同的值时,
  30. 此时就发生了样式的冲突。
  31. 发生样式冲突时,应用哪个样式由选择器的权重(优先级)决定
  32. 选择器的权重
  33. 内联样式(或者叫行内样式) 1,0,0,0
  34. id选择器 0,1,0,0
  35. 类和伪类选择器 0,0,1,0
  36. 元素选择器 0,0,0,1
  37. 通配选择器 0,0,0,0
  38. 继承的样式 没有优先级
  39. 值越大,优先级越高(权重越大),越优先显示
  40. 比较优先级时,需要将所有的选择器的优先级进行相加计算,最后优先级越高,
  41. 则越优先显示(分组选择器是单独计算的)
  42. 选择器的累加不会超过其最大的数量级,即类选择器再高也不会超过id选择器
  43. 如果优先级计算后相同,此时则优先使用靠下的样式
  44. 选择器写的越具体,优先级越高
  45. 可以在某一个样式的后边添加 !important ,则此时该样式会获取到最高的优先级,
  46. 甚至超过内联样式。
  47. 注意:在开发中 !important 一定要慎用,因为一旦加上以后就很难修改了
  48. */
  49. *{
  50. font-size: 50px;
  51. }
  52. div{
  53. font-size: 20px;
  54. }
  55. </style>
  56. </head>
  57. <body>
  58. <div id="box" class="red d1 d2" style="background-color: chocolate;">
  59. 这是一个div
  60. <span>这是div中的span</span>
  61. </div>
  62. </body>
  63. </html>