Colin Ricardo
Colin Ricardo

Reputation: 17239

Root div padding React (Styled Components)

I have a simple React App, using Redux's Provider to wrap my App component.

import React from 'react';
import ReactDOM from 'react-dom';
import styled from 'styled-components';
import { Provider } from 'react-redux';
import App from './App';
import store from './store';
import registerServiceWorker from './registerServiceWorker';

const MainContainer = styled.div`
  margin: 0;
  padding: 0;
  height: 100vh;
  background-color: red;
`;

ReactDOM.render(
  <MainContainer>
    <Provider store={store}>
      <App />
    </Provider>
  </MainContainer>,
  document.getElementById('root'),
);

registerServiceWorker();

However, when this app renders, there's a white gap around the edge (all sides) of the screen. What's the correct way to override the body tag so that the App content goes to the edge of the screen?

White Margin should not be there.

Upvotes: 2

Views: 8022

Answers (5)

patrick
patrick

Reputation: 16949

 function App() {
      document.body.style.padding = "0"; // these did the trick
      document.body.style.margin = "0"; // these did the trick

// using App2 because of async not allowed at root level
    
      return <App2></App2>;
    }

Upvotes: 0

lemontea0
lemontea0

Reputation: 1

In your "App.css" write this :

body {
  overflow-y: hidden;
}

That's working for my home page.

Upvotes: 0

inBlackAndWhite
inBlackAndWhite

Reputation: 91

For styled components v4 and onwards use createGlobalStyle instead:

import { createGlobalStyle } from "styled-components"

const GlobalStyle = createGlobalStyle`
  body {
    color: red;
  }
`

// later in your app's render method
<React.Fragment>
  <Navigation />
  <OtherImportantTopLevelComponentStuff />
  <GlobalStyle />
</React.Fragment>

Styled Components FAQs

Upvotes: 0

Tholle
Tholle

Reputation: 112777

That's the default styling of your browser. You could use something like Normalize.css, or simply remove the margin and padding of the body yourself.

body {
  margin: 0;
  padding: 0;
}

You can do this with injectGlobal.

import { injectGlobal } from 'styled-components';

injectGlobal`
  body {
    margin: 0;
    padding: 0;
  }
`;

Upvotes: 8

Colin Ricardo
Colin Ricardo

Reputation: 17239

Thanks for the answers, but I was looking for a Styled Components specific answer.

Turns out that Styled Components has a helper method, injectGlobal, which can override the global body tag.

Using this, one can set the desired properties – in this case, no margin / padding. So, adding the following to index.js solves the issue.

import { injectGlobal } from 'styled-components';

injectGlobal`
  body {
    margin: 0;
    padding: 0;
  }
`;

Upvotes: 2

Related Questions