【问题标题】:why is the specificity in CSS not getting implemented in my code? [duplicate]为什么 CSS 的特殊性没有在我的代码中实现? [复制]
【发布时间】:2021-04-07 17:32:06
【问题描述】:

这是我在 CSS 中测试特异性的代码。ul#Drinks 的特异性是 (1,0,1) 而 .hello 的特异性是 (0,1,0)。谁能告诉为什么列表中的第二项(Mountain Dew)是棕色而不是蓝色?这将是一个很大的帮助

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Specificity</title>
    <style>
        .hello{
            color:brown;
            font-weight: bold;
            font-style: unset;
        }
       ul#Drinks{
            color:darkblue;
            font-size: 30px; 
            font-style: italic;   
        }
    </style>
</head>
<body>
    <ul id="Drinks">
        <li>fanta</li>
        <li class="hello">Mountain Dew</li>
        <li>Pepsi</li>
    </ul>
    
</body>
</html>

【问题讨论】:

  • 在这种情况下没有明确的规则。您已经直接为 li 提到了颜色,因此它会覆盖父级。如果您提供了ul#Drinks li,那么它将是蓝色的。
  • 正如 m4n0 所说。特殊性规则用于其他情况(当我们对一个元素有更多规则时,而不是父子元素)。为了更好地理解,请使用&lt;li&gt;blue &lt;span class="hello"&gt;brown&lt;/span&gt; blue&lt;/li&gt;。嵌套的 .hello 是棕色的,UL 的其余部分是蓝色的。
  • 非常感谢!

标签: html css tags css-specificity


【解决方案1】:

在 CSS 中,“特异性”适用于将属性应用于具有多个类的单个元素或选择器所针对的其他属性(了解更多信息 here)。在这种情况下,无需担心特殊性,因为您的 &lt;li&gt; 只有一个具有相应 CSS 的类,并且其样式将覆盖其父类的样式。

【讨论】:

    【解决方案2】:

    试试这个:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Specificity</title>
        <style>
            .hello{
                color:brown;
                font-weight: bold;
                font-style: unset;
            }
           ul[id="Drinks"] * {
                color: darkblue;
                font-size: 30px; 
                font-style: italic;   
            }
        </style>
    </head>
    <body>
        <ul id="Drinks">
            <li>fanta</li>
            <li class="hello">Mountain Dew</li>
            <li>Pepsi</li>
        </ul>
        
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-12
      • 2011-06-07
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多