Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using container in React-Boostrap my body's background-color is overwritten

I am in the process of introducing myself to react bootstrap. So far I have the following in npm:

npm install react-bootstrap bootstrap

From there, I have made my parent element in App.js a container:

import React from 'react';
import {Link, Route, BrowserRouter, Switch} from 'react-router-dom'
import 'bootstrap/dist/css/bootstrap.min.css';
    
function App() {
  return (
    <BrowserRouter>
    <div className="App container">
       ...
    </div>
    </BrowserRouter>
  );
}

And I also have bootstrap imported according to the reactBootStrap documentation:

import 'bootstrap/dist/css/bootstrap.min.css';

Next, I have edited my index.css so that my my container class has a white background and my body has a teal background:

body {
    background-color: teal;
}
    
.container {
    background-color: white;
}

The issue I'm having is that my entire page shows a white background. When I open up inspect, it shows that my body did have a teal background-color, but it was overridden, but I am not sure when in my code it was overwritten. Does anyone have any experience with such an issue? My goal is to have a white container, with a teal background on either side of the container when I view my page.

like image 238
David Reke Avatar asked Aug 04 '20 18:08

David Reke


1 Answers

CSS stands for Cascading Style Sheets - Cascading being the key word here. In the React template the index.html (where index.css is applied) actually loads App.js and and App.css afterwards.

Consequently, this means that any file applied or loaded after index.css that have a matching CSS rule will overwrite the CSS rules you added in index.css.

The best solution here is to add import "./App.css" to the top of your ./App.js and add your rules to App.css. That way they are loaded and the end of chain and they should overwrite everything applied beforehand:

import React from 'react';
import {Link, Route, BrowserRouter, Switch} from 'react-router-dom'
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css'

function App() {
  return (
    <BrowserRouter>
    <div className="App container">
        text in a container
    </div>
    </BrowserRouter>

  );
}

export default App;

Then, in your App.css, add:

body {
        background-color: teal;
}

.container{
        background-color: white;
}

After doing this you essentially end up with the following:

enter image description here

You can read more about cascading here on SO in the following question: What is the meaning of "cascading' in CSS?

like image 80
Adam Waldenberg Avatar answered Oct 05 '22 03:10

Adam Waldenberg