Search code examples
csscss-specificity

How to prioritize a CSS class?


I'm referencing to some bootstrap style sheet and there's a definition for

.badge {
    display: inline-block;
    min-width: 10px;
    padding: 3px 7px;
    font-size: 12px;
    font-weight: 700;
    line-height: 1;
    color: #fff;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    background-color: #777;
    border-radius: 10px;
}
.alert-success {
    color: #3c763d;
    background-color: #dff0d8;
    border-color: #d6e9c6;
}

I want to use this style but due to my HTML class="alert-success badge", it's overridden by the other definition

.panel-default>.panel-heading .badge {
    color: #f5f5f5;
    background-color: #333;
}

Now that the latter definition is more specific, it prioritize over my desired CSS. How can I resolve this?

EDIT: There are a lot more other classes that have this issue. Is there a solution I don't need to specify them one by one?


Solution

  • With CSS Specificity, you should just override the more specific selector with your own.

    .panel-default > .panel-heading .badge.alert-success {
        color: #3c763d;
        background-color: #dff0d8;
        border-color: #d6e9c6;
    }
    

    Edit: Other options can include:

    1. Removing/Altering the offending CSS file (difficult with bootstrap, but doable, and maintenance headache if you decide to update bootstrap.css)
      • Update/remove offending selectors
      • Adding :not() selector to avoid certain scenarios
    2. Altering your HTML Structure so that it does NOT follow the offending CSS selectors.
      • Changing class names and/or using new ones
      • Inserting/Deleting additional nested divs/elements (to avoid > direct-child selector)

    Thankfully, if you have lots of classes to update, a smart regex replace is your best friend, but that's another topic.