Fixing bugs with Outlook specific CSS

From Stig Morten Myre’s post at https://cm.engineering/fixing-bugs-with-outlook-specific-css-f4b8ae5be4f4.

Conditional comments

Thankfully, when Outlook 2007 came out, the Office team took a cue from Internet Explorer and implemented support for conditional comments, as James Edwards discovered and shared in a Sitepoint article.

Conditional comments allow us to add bits of HTML that are only read by the Word-based versions of Outlook.

Conditional stylesheet

The most common way to code Outlook targeted CSS is by placing an embedded stylesheet inside a conditional comment.

For Outlook only:

<!--[if mso]>
 <style type="text/css">
   ul {
     margin: 0 0 0 24px !important;
   }
 </style>
<![endif]-->

For Non-Outlook only:

<!--[if !mso]><!-- -->
  Content targeted at non-Outlook users goes here
<!--<![endif]-->

Note the !important declaration which is needed to override inline styles.

The stylesheet will be parsed by the Word-based versions of Outlook. To other rendering engines, the whole block of code will look like an HTML comment they should ignore.

Although I’ve never needed to, you can get more specific with conditional comments that target specific versions of Outlook. Should you need to, here are the mso version numbers that correspond to each Word-based Outlook version.

<!--[if mso 12]>Outlook 2007<![endif]-->
<!--[if mso 14]>Outlook 2010<![endif]-->
<!--[if mso 15]>Outlook 2013<![endif]-->
<!--[if mso 16]>Outlook 2016<![endif]-->

Conditional classes

Paul Irish came up with the clever concept of using conditional comments to add different classes to the element when viewed in Internet Explorer.

You may have seen some variation of this in the source code of a web page.

<!--[if IE]><html class="ie"><![endif]-->
<!--[if !IE]><!--><html><!--<![endif]-->

The .ie class (or a version specific class) can then be used to prefix a CSS selector in your main stylesheet. The result is a rule that will only be matched in Internet Explorer.

<style type="text/css">
  .ie p {
    font-size: 18px !important;
  }
</style>

This exact code actually works in the older versions of Outlook that were based on Internet Explorer. These clients would render the email with whatever version of Internet Explorer was installed on the computer, so you could target specific Internet Explorer version, but not specific Outlook versions like 2000 or 2002.

This approach can be used to work around the lack of media query support in old Internet Explorer versions when coding mobile-first emails. Simply repeat the desktop styles outside of the media query, and give each selector an .ie prefix.

<style type="text/css">
  .layout {
    width: 320px;
  }
  @media (min-width: 620px) {
    .layout {
      width: 600px !important;
    }
  }
  .ie .layout {
    width: 600px !important;
  }
</style>