How to set a background image for all pages in reactjs

Viewed 909

I tried to set a image to all pages as background. I have tried to set the style of the body tag of index.html

<body style="background-image: url(%PUBLIC_URL%/bp.jpg)">

But this did not do anything. So I tried to add it to the body tag in index.css in src/. I have moved the picture from the public folder to /src.

But this did not do anything too.

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-image: url("./bg.jpg");
}

So my last try was the App.css where my routing is:

App.js:

import './App.css';
import { BrowserRouter as Router, Route } from "react-router-dom";
import CharacterFormView from "./views/CharacterFormView";
import SkillTreeView from "./views/SkillTreeView";

function App() {
  return (
    <div className="App">
      <Router>

        <Route exact path="/" component={CharacterFormView}/>
        <Route path="/character-form" component={CharacterFormView}/>
        <Route path="/skill-trees" component={SkillTreeView}/>

      </Router>
    </div>
  );
}

export default App;

App.css:

    .App {
      text-align: center;
      background: url("./bg.jpg") no-repeat;
      background-size: cover;
    
    }

This last try set the background image to the first two routes "/" and "/character-form". Even there it is not full screen only till the half of the page. If I go to "/skill-trees" - there is no image in the background

So how can I set the same picture as background img for all pages? The image should not repeat just full screen. I'm sure there's a better way as setting it in every .css file of my project.

Thanks in advance.

1 Answers

The background can be included in your App.css, but you need to use it like this:

 .App {
      text-align: center;
      background-image: url("./bg.jpg"); // here you had it wrong
      background-size: cover;
    }

This way your background will be rendered in your main component, App.js in your case, therefore, in all its children

Related