Search code examples
csshovercss-selectorscss-specificity

How to make sure color is overwritten on hover?


HTML:

<div class="hovertest" style="background-color: #fff">
    Test 1
</div>
<div class="hovertest" style="background-color: #eee">
    Test 2
</div>

CSS:

.hovertest:hover {
     background-color: #000;
}

The hover color does not get applied due to the higher specificity of the inline color style. Same problem if I give an ID to the divs and apply their individual color in the ID styling. I want to share the hover color definition across both divs (or more), while displaying their unique color on non-hover. Is this possible without a lot of redundant css?


Solution

  • You can outweigh any specificity of other declarations in CSS by setting !important after the value. Overriding this is only possible with another declaration with !important.

    .hovertest:hover {
        background-color: black !important;
    }
    
    #hovertest:hover {
        background-color: red; /* Even using an ID won't override `!important` */
    }
    

    But be careful! Using !important in your CSS can result in some really tricky issues. It's often more useful to write your CSS in a way where you avoid using it as much as possible.

    Don't use !important reactive, use it preventive.