Home

Override inline styles from CSS

A quick hæck, to save your neck

The bellow hack is here to save you from getting fired. You are welcome!


Inline styles want to make this blue. Ha! You got no power here.

The Original component

criminal.html
<div class="demo" style="color: blue; text-align: center; background-color: beige">
  Inline styles want to make this blue. Ha! You got no power here.
</div>

The criminal HTML

savior.css
.demo[style*='color: blue'] {
  color: green !important;
}

The savior CSS

Inline styles want to make this blue. Ha! You got no power here.

The rescued component

Why would you use this

With the large adoption of modern JavaScript frameworks like Angular 2+, React and Vue, there has been an increased usage of style="..." in HTML markup.

Whats worse: often times style="..." is being dynamically changed.

Whats worse 2: often times it is being updated inside a component from a third party library, so you can’t easily remove it.

Whats worse 3: your task requires you to stop that dynamic styling and apply a more specific style that is relevant to your application.

Whats worse 4: the third party library did not expose a nice API for you to do that.

What to do now?

Play with the source code, add the API and make a pull request. Well, in theory, yes…

In practice, your boss is in a hurry to deliver that feature. The !important hack above shall save you this time.

Observations

While it has been a long road where adding inline <script> or styles="..." in markup was considered a terrible practice, that notion is now beginning to be more debatable with the likes of JSX and CSS in JS. Front end frameworks in general have been shifting to a more component based approach to the separation of concerns.

With that being said, both style="..." and !important are not to be used lightly, as they can make things hard to debug and are generally considered bad practices in dealing with CSS specificity.

A good resource on when to use !important can be found here.