Themetry is no longer operational. This site is here for archival purposes. See what Leland is working on at le.land.

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?

  1. No way to manipulate pseudoclasses.
  2. Need an !important flag to override.
  3. 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.

Previous Post
Preventing output of empty entry footer markup
Next Post
Realizing not every theme needs a layout editor