温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

CSS中选择器优先级与!important权重的示例分析

发布时间:2021-01-05 10:23:10 来源:亿速云 阅读:165 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关CSS中选择器优先级与!important权重的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

CSS中的选择器优先级与!important权重

  • .class选择器要高于标签选择器。

  • #id选择器要高于.class选择器。

  • 标签选择器是优先级最低的选择器。

  • !important的属性它的权重值优先级最高的,大于所有的选择器。

标签选择器和.class选择器

让我们进入标签选择器和.class选择器谁的优先级高实践,实践内容如:将HTML页面中的h3标签设置文本颜色。

代码块

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>优先级</title>
    <style>
        h3{
           color: red; /*红色*/
       }
       .box{
            color: springgreen; /*绿色*/
       }
    </style>
</head>
  
<body>
    <h3 class="box">微笑是最初的信仰</h3>
</body>
</html>

结果图

CSS中选择器优先级与!important权重的示例分析

.class选择器和id选择器

让我们进入.class选择器和id选择器谁的优先级高实践,实践内容如:将HTML页面中的h3标签设置文本颜色。

代码块

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>优先级</title>
    <style>
       h3{
           color: red; /*红色*/
       }
       .box{
            color: springgreen; /*绿色*/
       }
       #box{
           color:blue; /*蓝色*/
       }
    </style>
</head>
  
<body>
   <h3 class="box" id="box">微笑是最初的信仰</h3>
</body>
</html>

结果图

CSS中选择器优先级与!important权重的示例分析

!important权重使用

现在我们知道了标签选择器优先级最低,那么笔者将标签选择器添加!important属性呢,谁的优先级更高呢?
!important权重使用格式如下:

color: red !important; /*红色*/

注意:属性:值 !important属性值用空格隔开即可。

让我们进入 !important属性使用实践,看看!important属性威力有多大哈。

代码块

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>!important使用</title>
    <style>
       h3{
           color: red !important; /*红色*/
       }
       .box{
            color: springgreen; /*绿色*/
       }
       #box{
           color:blue; /*蓝色*/
       }
    </style>
</head>
  
<body>
   <h3 class="box" id="box">微笑是最初的信仰</h3>
</body>
</html>

结果图

CSS中选择器优先级与!important权重的示例分析

优先级从低到高如:标签选择器、.class选择器、#id选择器、!important属性

关于“CSS中选择器优先级与!important权重的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI