July 12, 2022

Readable inlined CSS

Without judgement: there are many developers who manually inline CSS in their HTML emails. This post is aimed at developers who choose or have to manually inline their CSS.

If you’re reading this and not in the world of HTML email development, the short explanation is CSS has to be inlined out of necessity and not by choise.

I’m not going to dive into the maintainabiliy issues of inlined CSS and why you should avoid it if you can. What I want to discuss is the readability of inlined CSS. Readble code is very valuable; particularly in a team environment. If you don’t put an effort to keep your code readable, you’re hurting yourself and your team.

When you write CSS in a ruleset, you probably use whitespace to keep it readable like so:

.my-class {
  color: #000;
  fake-property: fake-value;
}

Besides the indentation, you most likely add a space between the property name and the value:

property: value;

I see developers trying to do the same when manually inlining their CSS:

<div style="color: #fff; property: value; fake-property: value;"></div>
<div style="color: #fff; property: value; fake-property: another-value; margin: 10px 0 30px; padding: 10px 20px;"></div>

The space between a property name and its value is equal in size to the space between a value and the following property. This makes it harder for you as a human to scan pairs. It simply takes your brain longer to parse the CSS.

A more readable alternative would be to stack the properties like you would when writing full rulesets:

<div style="
  color: #fff; 
  property: value; 
  fake-property: value;"
>
</div>

I know this is not everyone’s cup of tea. It’s not the only approach though. You can keep everything in one line and omit the space between a property and its value:

<div style="color:#fff; property:value; fake-property:value;"></div>

You end up with CSS that is a lot easier to scan and parse as a human. You can compare the readability of the two approaches below:

<div style="color: #fff; property: value; fake-property: another-value; margin: 10px 0 30px; padding: 10px 20px;"></div>
<div style="color:#fff; property:value; fake-property:another-value; margin:10px 0 30px; padding:10px 20px;"></div>