【问题标题】:When using container in React-Boostrap my body's background-color is overwritten在 React-Bootstrap 中使用容器时,我的身体的背景颜色被覆盖
【发布时间】:2020-11-24 21:54:31
【问题描述】:

我正在介绍自己以响应引导程序。到目前为止,我在 npm 中有以下内容:

npm install react-bootstrap bootstrap

从那里,我将App.js 中的父元素创建为容器:

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>
  );
}

而且我还根据 reactBootStrap 文档导入了引导程序:

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

接下来,我编辑了我的index.css,使我的容器类具有白色背景,而我的主体具有蓝绿色背景:

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

我遇到的问题是我的整个页面显示为白色背景。当我打开检查时,它显示我的身体确实有一个蓝绿色background-color,但它被覆盖了,但我不确定我的代码何时被覆盖。有没有人有这样的问题的经验?我的目标是拥有一个白色容器,当我查看我的页面时,容器的任一侧都有蓝绿色背景。

【问题讨论】:

  • 例如在 Chrome 中,当你检查元素时,你可以看到 active 属性,相关的类名就在它上面,检查它是随机字符串还是明确的

标签: css reactjs react-bootstrap


【解决方案1】:

CSS 代表 Cascading Style Sheets - Cascading 是这里的关键词。在 React 模板中,index.html(应用了index.css)实际上随后加载了App.jsApp.css

因此,这意味着在 index.css 之后应用或加载的任何具有匹配 CSS 规则的文件都将覆盖您在 index.css 中添加的 CSS 规则。

这里最好的解决方案是将import "./App.css" 添加到您的./App.js 的顶部,并将您的规则添加到App.css。这样它们就被加载并结束了链,它们应该覆盖预先应用的所有内容:

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;

然后,在您的 App.css 中,添加:

body {
        background-color: teal;
}

.container{
        background-color: white;
}

完成此操作后,您基本上会得到以下结果:

您可以在以下问题中阅读有关 SO 级联的更多信息: What is the meaning of "cascading' in CSS?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 2013-02-09
    • 2018-04-29
    • 1970-01-01
    • 2019-10-14
    相关资源
    最近更新 更多