◆

CSS 样式优先级规则与示例详解

2023-02-02 01:370

优先级顺序

!important > 行内样式 > ID 选择器 > 类选择器 > 标签 > 通配符 > 继承 > 浏览器默认属性

示例

如下所示我们通过各类选项设置 p 标签的背景颜色,最后展示的颜色是 background: red!important;。

  • 如果将 #stylePriority p 中 background 的 important 去掉,将会展示行内样式的背景 style="background: pink"
  • 如果删除行内样式,展示的将是 ID 选择器设置的背景: #pId {background: green;}
  • 如果继续删除 ID 选择器,展示的将是类选择器设置的背景: .pClass {background: blue}
  • 如果继续删除类选择器,展示的将是标签选择器设置的背景: p {background: red}
  • 如果继续删除标签选择器,展示的将是从 h3 属性上继承背景颜色 #stylePriority {background: yellow},如示例二

tip

通配符就不演示了---会影响整体页面的样式

::: demo [vanilla]

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <h3 id="stylePriority">
      <p class="pClass" id="pId" style="background: pink">这是一个p1元素</p>
    </h3>
    <style>
      #stylePriority #pId {
        background: green;
      }

      #stylePriority .pClass {
        background: blue;
      }

      #stylePriority p {
        font-size: 30px;
        border: 1px solid blue;
        background: red !important;
      }

      #stylePriority {
        background: yellow;
        color: purple;
        height: 80px;
        font-style: italic;
      }
    </style>
  </body>
</html>
{
  "show": true
}

:::

示例二

::: demo [vanilla]

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <h3 id="stylePriorityOne">
      <p>这是一个p1元素</p>
    </h3>
    <style>
      #stylePriorityOne {
        background: yellow;
      }
    </style>
  </body>
</html>
{
  "show": true
}

:::

💬留言板0

还没有留言,来发表第一条吧~

PAGE LOAD / LIVECSS 样式优先级规则与示例详解加载中