【发布时间】:2020-04-16 20:33:52
【问题描述】:
我正在创建一个简单的 React 应用(使用 create react app 作为起点),其中 App.js 返回以下内容:
return (
<div className="App">
<NavBar />
<Main />
</div>
);
}
export default App;
我正在尝试使用以下内容将图像添加到 Main:
return (
<div className="bg">
<LogInSignUpModal />
</div>
);
}
export default Main;
在 Main.css 文件中,我有以下内容:
/* The image used */
background-image: url("../../images/WorkoutRack.jpg");
/* Full height */
height: 100%;
width: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
不幸的是,图像不会出现在主组件中(主组件应该占据 NavBar 下方的整个页面。我尝试了在其他 StackOverflow 响应中找到的许多不同解决方案,但没有一个有效。我是什么这里不见了?
【问题讨论】:
-
确保包裹这个
bg元素的所有元素的高度设置为100%。这包括html、body和#root。打开开发控制台,包装此bg元素的任何元素都应设置为height: 100%;。 -
尝试 background 而不是 background-image
-
@MattCarlotta 谢谢 - 这似乎奏效了!我将 index.html(具有#root)存储在公用文件夹中,而所有组件都存储在 src 文件夹中。哪个最适合#root:在外部导入的 CSS 文件 中设置高度 100% 还是在 index.html 中设置?
-
@DanielS。很高兴你想出来了。您应该在外部 CSS 样式表中设置高度 - 使您的
index.html尽可能干净。如果你想知道为什么会这样,简单来说,未定义高度和宽度的父元素是 0px x 0px。因此,当孩子设置为 100%(高度或宽度)时……它是 0px 的 100%。这就是为什么您必须遍历 DOM 树并将所有父元素设置为视图的 100% 的原因——除非您在px/em/rem...等中定义高度/宽度,那么您只需要设置最近的父级的样式)。
标签: css reactjs components