'How can I apply style to DOM elements added by Gatsby?

Gatsby adds elements to the DOM.

These include:

  • #___gatsby
  • #gatsby-focus-wrapper

Because these styles are not user-created, component-scoped styles can't be applied to them.

Gatsby provides the means to add a global style sheet: We can create a stylesheet and import it into a layout component. However, rules targeting the elements that Gatsby adds to the DOM are not applied.

There are some very basic things that become very difficult and hacky to do unless we can style these elements.

Is there a non-hacky way to add a stylesheet that will apply it's rules to all targets?



Solution 1:[1]

Global styles can target all DOM elements despite who has added there, depending on your interpreter. For example, Gatsby's home page (built-in Gatsby) targets the gatsby-focus-wrapper and the ___gatsby identifiers with the * selector:

enter image description here

  • gatsby-focus-wrapper is added automatically by @reach/router so it can automatically manage the focus as part of making sure sites are usable by screen readers. More details:

  • ___gatsby is the root of the project, the main wrapper. It can be tweaked using a custom HTML. If you place a html.js in the /src folder of your project or by running:

    cp .cache/default-html.js src/html.js
    

    You will see the ___gatsby id:

    <div
       key={`body`}
       id="___gatsby"
       dangerouslySetInnerHTML={{ __html: this.props.body }}
    />
    

    Gatsby will take it as a base of your HTML. You can customize the id if you want there.

That said, all global styles apply to all DOM elements, even the ones added by Gatsby. I've tested it in some of my projects by adding any CSS file:

 #___gatsby {
  background: red;
}

And it changes the background color accordingly. Double-check your global styles because the following statements are not true at all I'm afraid:

However, rules targeting the elements that Gatsby adds to the DOM are not applied.

Because these styles are not user-created, component-scoped styles can't be applied to them.

If your global styles are added with styled-components or other CSS-in-JS sources (emotion, etc) check that the plugins are well configured. You can also try adding them using the shared APIs gatsby-ssr.js and gatsby-browser.js files with wrapRootElement or wrapPageElement within your custom layout component.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1