Skip to content
Advertisement

Styled component doesn’t override inline styles

I’m trying to override third party component inline style.

I followed the doc how can i override inline styles

So, I used &[style] to override the inline style but this is not working.

The third party component I use is CookieConsent

Right now, my component is looking like that:

JavaScript

I also tried how can i override styles with higher specificity without success.

The only way I found to override the style is doing something like that and use !important

JavaScript

and also tried, without success

JavaScript

The docs seems pretty clear but I didn’t succeed.

Did I miss something? Is that possible or should I use the style component props?

Advertisement

Answer

From the documentation page you linked:

Inline styles will always take precedence over external CSS, so you cannot override it by simply increasing specificity.

Let’s stop right there. Styled Components adds classes to elements. In HTML/CSS, style attribute styles will almost always trump class-based styles; there is nothing Styled Components (or any other class-based library) can do to change that … unless you use a “hack” with !important that is …

There is a neat trick however, which is to use the style element-attr CSS Selector in conjunction with !important:

The !important is an essential part of that hack, and so the (working) code you posted:

JavaScript

is both correct, and your only option.

If you really want to override style attributes … override the style attributes 🙂 Don’t use Styled Components, use a style prop on your element (or in your case, ask react-cookie-consent to take a style prop to achieve that effect).

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement