Overwrite Inline Styles with CSS

We often find ourselves in situations when we want to overwrite a style we don’t have access to, it’s hard to find or we want to rewrite with CSS a style that has been written in the HTML code or has been set with Javascrpt.
In this article we’re going to discuss the strength of different style declarations and how can we overwrite them.

Let’s say we have the sentence below to start with.

<p>This is our <span id="highlighted">demo text</span>.</p>


To highlight the span tag we would normally use CSS styles like this:

#highlighted {
    color: red;
}

We can overwrite this if we define another color after this line in the stylesheet because always the lower rules apply. In this case the text will be blue:

#highlighted {
    color: red;
}
#highlighted {
    color: blue;
}

We can target more accurately the span, to set it’s color. In both cases below the color of the highlighted text will be green.

span#highlighted {
    color: green;
}
#highlighted {
    color: red;
}

p #highlighted {
    color: green;
}
#highlighted {
    color: red;
}

Use the !important sign to override a property, regardless of its position in the document. An “!important” declaration is always stronger than one without it. It’s recommended to use these only if it’s really necessary. In our example below the text will be red.

p #highlighted {
    color: green;
}
#highlighted {
    color: red !important;
}

HTML inline styles are stronger than the CSS so in this case the text will be grey, but we can overwrite this with an !important rule from the stylesheet.

p #highlighted {
    color: green;
}
<p>This is our <span id="highlighted" style="color: grey;">demo text</span>.</p>

In some cases the style is reset with JavaScript / jQuery and we can’t overwrite it with the stylesheets. In this case we can use the strongest CSS declaration which overwrites everything:

#highlighted[style] {
   color: yellow !important;
}