Irrelefant
Irrelefant

Reputation: 125

Remove margin from body in React

I'm new to React and currently in the process of building a website, however I cannot get rid of the margin of the body. My css in inside the index.js component and looks like this:

<style jsx>{`
  body {
    margin: 0px;
    padding: 0px;
  }
`}</style>

Upvotes: 10

Views: 27518

Answers (5)

Shawemra_Lvr
Shawemra_Lvr

Reputation: 25

Setting global styles in NEXT.js is like so:

  • Create a top-level styles directory and a global.css file.
  • Add the following CSS inside styles/global.css. This code resets some styles and changes the color of the a tag:
html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu,
    Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  line-height: 1.6;
  font-size: 18px;
}
...
  • Finally, import the CSS file inside the pages/_app.js file you've created earlier on:
// `pages/_app.js`
import '../styles/global.css';

Answer adjusted from the docs.

Upvotes: 0

Uladz Kha
Uladz Kha

Reputation: 2354

You can simply create a global.css, (if it doesn't exist already) with css style:

html,
body {
  padding: 0;
  margin: 0;
}

and import this file in _app.jsx:

import "./global.css";

Upvotes: 7

Irrelefant
Irrelefant

Reputation: 125

Thanks for your answer, but I just figured it out. The problem is that I'm using Next.js, which means I don't really have a body tag since it't provided by the "pages" feature from Next. The solution for me was to add the "global" attribute to the jsx which gives me the required access.
Just like this:

   <style jsx global>{`
         body{
             margin: 0px;
             padding: 0px;
         }
        `}</style>

Upvotes: 0

san
san

Reputation: 1693

You should use global with jsx style

<div>
    <style jsx global>{`
      body {
        margin: 0px;
        padding: 0px;
      }
    `}</style>
  </div>

Upvotes: 9

amcquaid
amcquaid

Reputation: 539

Where is your root defined? If it's within the body, you won't have access to the body element. Add it to your css or as an in-line style in your index.html.

Inline index.html

<body style="margin: 0px; padding: 0px;">
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
</body>

CSS

body {
    margin: 0px;
    padding: 0px;
}

Upvotes: 8

Related Questions