ReactJS + React Router:如何居中div?

Jo *_* Ko 8 html javascript css reactjs react-router

我目前已经设置了一个ReactJS + React Router项目,并在Chrome开发工具中的元素下方显示:

<body>
  <div class="wrapper">
    <div data-reactroot>
      <div>
        <div class="container">Center Me</div>
      </div>
    </div>
  </div>
</body>
Run Code Online (Sandbox Code Playgroud)

带有样式,没有用于class="wrapper"

.container {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
Run Code Online (Sandbox Code Playgroud)

但是,<div class="container">Center Me</div>它停留在顶部,并且水平居中,而不是垂直居中。

我检查了该div的大小,它非常短,但占用了浏览器页面的整个宽度。

我可能做错了什么?我如何居中<div class="container">Center Me</div>?我什至试图设置100% for width and height一个更高的级别,但仍然无法正常工作。

Trọ*_*ông 18

只是:

<div style={{display: 'flex',  justifyContent:'center', alignItems:'center', height: '100vh'}}>
    <h1> I am centered </h1>
</div>
Run Code Online (Sandbox Code Playgroud)

或CSS:

<div style={{display: 'flex',  justifyContent:'center', alignItems:'center', height: '100vh'}}>
    <h1> I am centered </h1>
</div>
Run Code Online (Sandbox Code Playgroud)
.centered {
  height: 100vh; /* Magic here */
  display: flex;
  justify-content: center;
  align-items: center;
}
Run Code Online (Sandbox Code Playgroud)


Win*_*Win 6

这是一个代码示例,它基本上重新创建了您的页面,但没有做出反应。希望这对您有所帮助,如果您有任何疑问,请直接离开。

html, body{
  width: 100%;
  height: 100%;
}

.wrapper{
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.container {
  height: 300px;
  width: 300px;
  background: black;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}
Run Code Online (Sandbox Code Playgroud)
<html>
<body>
  <div class="wrapper">
    <div data-reactroot>
      <div class="container">
        <div>
          <!-- Anything below this line will be centered -->
          <div>Hello World!</div>
          <div>Center Me</div>
          <!-- Anything above this line will be centered -->
        </div>
      </div>
    </div>
  </div>
</body>
<html>
Run Code Online (Sandbox Code Playgroud)


mat*_*hew 0

在 React 中,您需要使用 className 而不是 class。

className="wrapper"
Run Code Online (Sandbox Code Playgroud)