Is there a way to increase specificity by adding the element with Emotion?

Viewed 3172

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.

1 Answers

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.

Related