• Advanced
  • Existing CSS

Existing CSS

There are a couple of implementation details that you should be aware of, if you choose to use this library together with existing CSS.

This library only attaches the provided classes to the DOM nodes via the className prop.

Styling normal React components

If you use the styled(MyComponent) notation and MyComponent does not render the passed-in className prop, then no styles will be applied. To avoid this issue, make sure your component attaches the passed-in className to a DOM node:

const MyComponent = () => (
  // Attach the passed-in className to the DOM node
  <div className={this.props.className} />
)

If you have pre-existing styles with a class, you can combine the global class with the passed-in one:

const MyComponent = ({ className }: any) => (
  // Attach the passed-in className to the DOM node
  <div className={`some-global-class ${className}`} />
)

Issues with specificity

If you apply a global class together with a styled component class, the result might not be what you're expecting. If a property is defined in both classes with the same specificity, the last one will win.

/* global.css */
.bg-blue {
  background-color: blue;
}
/* styles.module.css */
.bg-red {
  background-color: red;
}
// MyComponent.js
const MyComponent = styled.div(styles.bg)
 
// For some reason this component still has a red background,
// even though you're trying to override it with the "bg-blue" class!
render(<MyComponent className="bg-blue" />)

In the example above the class that takes precedence is the one defined later on the document, since usually global styles comes first it won't have an effect.

The solution is to bump up the specificity of the selectors in your stylesheet:

/* global.css */
body .blue-bg {
  background-color: blue;
}

Avoiding conflicts with third-party styles and scripts

If you deploy styled-components on a page you don't fully control, you may need to take precautions to ensure that your component styles don't conflict with those of the host page.

The most common problem is insufficient specificity. For example, consider a host page with this style rule:

body.my-body button {
  padding: 24px;
}

Since the rule contains a classname and two tag names, it has higher specificity than the single classname selector generated by CSS Modules:

styled.button(styles.myButton)

There's no way to give your components complete immunity from the host page's styles, but you can at least boost the specificity of their style rules with postcss-prefix-selector, which allows you to specify a CSS namespace for all of your components. A good namespace would be something like #my-widget, if all of your styled-components render in a container with id="my-widget", since ID selectors have more specificity than any number of classnames.