Javascript 如何在反应中垂直和水平地居中组件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52284288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:58:02  来源:igfitidea点击:

How to vertically and horizontally center a component in react?

javascriptcssreactjs

提问by James L.

How can I achieve absolute centering with CSS-in-JS? When I use the following code, my component moves across the screen. I guess the translate is being applied many times instead of just once. What's going on, and how can I fix it without using a library?

如何使用 CSS-in-JS 实现绝对居中?当我使用以下代码时,我的组件会在屏幕上移动。我想翻译被应用了很多次而不是一次。发生了什么,如何在不使用库的情况下修复它?

  render() {
      return (<ComponentASD 
        style={{
        position: 'absolute', left: '50%', top: '50%',
        transform: 'translate(-50%, -50%)'
      }} />);
    }

回答by erikryanmoore

Another option is to use flex-box.

另一种选择是使用 flex-box。

<div style={{
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
}}>
    Hello world
</div>

回答by Marcel

Your example code works well:

您的示例代码运行良好:

ReactDOM.render(
  <div
    style={{
        position: 'absolute', left: '50%', top: '50%',
        transform: 'translate(-50%, -50%)'
    }}
    >
    Hello, world!
  </div>,
  document.getElementById('root')
);

https://codepen.io/anon/pen/JaLLmX

https://codepen.io/anon/pen/JaLLmX

It has to do something with your layout.

它必须对您的布局做些什么。

回答by James L.

Thanks for the testing+comments! The styling ended up being fine, the issue was somehow caused by the layout of ComponentASD, which is actually MUI's CircularProgress https://material-ui.com/api/circular-progress/#demos

感谢测试+评论!样式最终很好,问题是由 ComponentASD 的布局引起的,这实际上是 MUI 的 CircularProgress https://material-ui.com/api/circular-progress/#demos

I wrapped that component in a divinside of render and applied the styling to the div, which fixed the problem (keeps it stationary and properly aligned).

我将该组件包裹在div渲染内部并将样式应用到 div,从而解决了问题(使其保持静止并正确对齐)。