代码之家  ›  专栏  ›  技术社区  ›  Frasher Gray

JsonWebapp中的CSS类优先级

  •  1
  • Frasher Gray  · 技术社区  · 1 年前

    我遇到了一个问题,无论我尝试什么,一个特定的班级 background-color 始终显示在屏幕上。

    代码:

    <style>
    .btnClass {
        border-radius:6px;
        padding: 5px;
        text-align:center;
        text-decoration:none;
        display: inline-block;
        font-size:1em;
    }
    .gray {
        background-color: #494949;
        border: 1px solid black;
        color: white;
    }
    .fill {
        width: 100%;
        height: 12%;
        background-color: lightcyan;
    }
    </style>
    
    <button class="btnClass @(ExampleBoolean ? "fill" : "fill gray")">Example Button</button>
    <button class="btnClass" @onclick="ChangeBool">Change Boolean</button>
    
    
    @code {
        private bool ExampleBoolean = false;
        
        private void ChangeBool()
        {
            ExampleBoolean = !ExampleBoolean;
        }
    }
    

    我首先尝试在整个比较之前填写填表类,如下所示:

    <button class="btnClass fill @(ExampleBoolean ? "" : "gray")">Example Button</button>
    

    和移动 fill 待以后 gray ,无论是在@位代码内部还是外部,但它们都不起作用。有人能解释一下发生了什么以及为什么吗?

    1 回复  |  直到 1 年前
        1
  •  1
  •   gunr2171    1 年前

    我不是CSS专家。我不知道为什么CSS会这样工作。

    你有两个CSS类:fill和grey,它们具有相同的属性 specificity 。您只能申请 background-color 一旦到达元素,CSS就会选择规则 那是最后写的 。请注意,这表示中定义的最后一种样式 <style> ,而不是在class属性中使用哪个类名。

    您可以在您的 <风格> 以便 .gray 最后。

    .btnClass {
        border-radius:6px;
        padding: 5px;
        text-align:center;
        text-decoration:none;
        display: inline-block;
        font-size:1em;
    }
    .fill {
        width: 100%;
        height: 12%;
        background-color: lightcyan;
    }
    .gray {
        background-color: #494949;
        border: 1px solid black;
        color: white;
    }
    <button class="btnClass fill">button with fill</button>
    <button class="btnClass fill gray">button with fill and grey</button>

    另一种选择是改变 .灰色 选择器更具体,例如 .fill.gray 。这意味着“元素是 二者都 CSS将看到这个新规则更具体,并正确地覆盖了来自 .fill .

    .btnClass {
        border-radius:6px;
        padding: 5px;
        text-align:center;
        text-decoration:none;
        display: inline-block;
        font-size:1em;
    }
    .fill.gray {
        background-color: #494949;
        border: 1px solid black;
        color: white;
    }
    .fill {
        width: 100%;
        height: 12%;
        background-color: lightcyan;
    }
    <按钮class=“btnClass fill”>填充按钮</按钮>
    <按钮class=“btnClass fill gray”>带填充和灰色的按钮</按钮>

    您可能希望重命名所有规则以遵循此“层次结构”。如果 fill 应仅用于以下元素 btnClass ,以及 gray 只存在于增强 填满 ,你可能会得到这样的结果:

    .btnClass {
      /* ... */
    }
    .btnClass.fill {
      /* ... */
    }
    .btnClass.fill.gray {
      /* ... */
    }
    

    你也可以 在上定义背景颜色 填满 ,并要求应用另一个颜色类来设置颜色。

    你也可以扇耳光 !important 到最后 .灰色 s 背景颜色 ,但我建议不要这样做。