Isolating styles for Internet Explorer with Styled Components

When supporting older browsers such as Internet Explorer 11 it is common to have styles for both modern browsers and then fallbacks for the older browsers. Recently I was thinking how I could organise my styles to make this distinction clear, showing the intent of the fallback styles. This article shows a simple way to do this using styled components.

The idea is to define two separate styled components; one for the new browsers and one with the fallbacks.

For example:

const IE11Component = styled.div`
  /* fallback styles */
`;

const ModernComponent = styled(IE11Component)`
  @supports (display: grid) {
    /* undo fallback styles if necessary */
    /* modern styles */
  }
`;

This will result in only the fallback styles in browsers which do not support @supports feature queries such as IE11. Browsers which do support feature queries will apply the rulesets defined in ModernComponent.

Now in your code you can simply use ModernComponent and when you drop support for IE11 all you have to do is:

  • copy the tagged template literal name from the IE11Component over to the ModernComponent - in this case `styled.div` would replace `styled(IE11Component)`
  • delete IE11Component
  • remove any style undos from ModernComponent
const ModernComponent = styled.div`
  @supports (display: grid) {
    /* modern styles */
  }
`;

The benefits of this approach are that the intent of the styles for old browser support is clear and it is obvious which code to delete when dropping support for old browsers.

Tags: CSS, Styled Components