使用不同组件的 CSS 定位做出反应

React using CSS positioning with different components

我正在尝试设置一个以主图为背景的登录页面。我试图在屏幕中心周围有两列彼此相邻。我的计划是在 CSS 中使用 body 标签 来设置 background-image 并设置 position: relative 所以我稍后可以使用 position: absolute 将其中包含文本的列置于 image/screen 的中心。但是,我使用的是 React,我使用 index.js 组件将其设置为相对并设置背景,然后我添加了一个 Home 组件 这将包含着陆页的其余部分,从必须设置为 position absolute 的两列开始。

在 index.js 样式组件中

body{
    background-image: url(../src/assets/HeroImage.jpg);
    height: 100vh;
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
    position: relative;
}

在主页样式组件中

.heroimage-text-container{
    background-color: red;
    height: 100px;
    position: absolute;
    top: 0;
    left: 0;
}

通过这种方式尝试发生的情况是,当位置设置为绝对位置时,heroimage-text-container 消失了。我知道如果这一切都在同一个组件中就不会发生,所以我希望这里有人可以帮助我解决这个问题。谢谢。

在这种情况下你应该使用弹性框。绝对使用相同的 class 它将重叠,因为它们将具有相同的属性。

body {
  background-image: url("https://images.unsplash.com/photo-1506716442075-1e2e0e5b1256?ixlib=rb-1.2.1&auto=format&fit=crop&w=1343&q=80");
  height: 100vh;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  position: relative;
}

.App {
  font-family: sans-serif;
  text-align: left;
  display: flex;
  flex-direction: row;
}

.heroimage-text-container {
  background-color: red;
  height: auto;
  margin: 10px;
  padding: 10px;
}

看看沙箱 https://codesandbox.io/s/bold-tdd-d39oc