Avoiding inline CSS at all costs
Whether it’s through a WordPress theme option or a JavaScript function, front-end developers occasionally have to implement dynamic CSS code to a page.
While there’s always more than one way to skin a cat, that way should never involve inline CSS.
Clarification on terminology
External CSS — when a stylesheet file is referenced in the head:
<link rel='stylesheet' href='https://themetry.com/wp-content/themes/markov/style.css' type='text/css' />
Internal CSS — CSS directly in the head:
<style>
body:before {
content: "I have some valid use cases.";
}
</style>
Inline CSS (the bad one):
<div style="font-size: 300%; color: red">This CSS can't be overridden without !important.</div>
Why not inline CSS?
- No way to manipulate pseudoclasses.
- Need an !important flag to override.
- If an !important flag is used inline, you need JavaScript to override.
Common use cases, and how to avoid
The Menu Toggle — Instead of jQuery’s toggle function:
$( ".menu-toggle" ).click(function() {
$( "body" ).toggleClass( "menu-toggled" );
});
Then style with CSS:
.menu-toggled .menu {
display: block;
}
Featured Images and Header Background Images — Use wp_add_inline_style() instead.
To reiterate, there’s never a case for inline CSS.