9

We have a styled component that and when it compiles it adds a class name such as this:

<div class="app">
    <a class="css-hash">link</a>
</div>

This is all good, except for instances where someone has CSS declared similar to the following:

.app a { color: red }

The .css-hash is no longer picked up if it has a color rule. This could be resolved if we could have emotion create the CSS in a manner like "a.css-hash". In that case whatever we have as part of emotion's .css-hash would be applied over other styles that are declared elsewhere in the page.

It's possible that we're approaching this incorrectly. I tried searching for a solution in various places, but with no luck.

amrinea
  • 553
  • 4
  • 12
  • You can use `!important` for example `.css-hash { color: blue !important; }` – Evik Ghazarian Jun 30 '20 at 15:56
  • @EvikGhazarian We could do that, but try to avoid using !important if possible because it causes other issues. If we can get Emotion to prefix the element to the CSS it generates, it would resolve our issue. That's what I'd like to figure out how to do. – amrinea Jun 30 '20 at 19:08

1 Answers1

28

You can use the & selector more than once to increase specificity:

import { css } from '@emotion/css'

const myClassName = css({
  // Using `&` twice to increase specificity
  '&&': {
    backgroundColor: 'red'
  }
})

const MyComponent = () => {
  return <div className={myClassName}>hello</div>
}

& will simply copy your classname, so if your class name is .css-hash, then && will become .css-hash.css-hash. You can use more & to further increase specificity.

See Sass Ampersand docs.

Pedro Cattori
  • 2,735
  • 1
  • 25
  • 43