How to vertically and horizontally center a component in react?

Viewed 101644

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?

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

Another option is to use flex-box.

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

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

It has to do something with your layout.

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

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

This is flexbox you will need to use this on the parent Component.

   .Parent {
        display: flex,
        flexFlow: row nowrap,
        justifyContent: center,
        alignItems: center,
    {

It will center the children vertically and horizontally You can also align each component as I've shown you below

render() {
  return (<Childcomponent 
    style={{
    display: flex,
    flexFlow: row nowrap,
    justifySelf: center,
    alignSelf: center,
  }} />);
}

If you want to have a properly scrollable list if the window's height is smaller than the content's height you want to center, you can do this (based on this CSS answer):

<div
style={{
  display: "table",
  position: "absolute",
  height: "100%",
  width: "100%",
  top: 0,
  left: 0
}}
>
<div
style={{
  display: "table-cell",
  verticalAlign: "middle",
  textAlign: "center"
}}
>
// Here comes the content you want to center
</div>
</div>

If you want to use it in a component just call it in the component:

.Login {
text-align: center;
background-color: #2681C6;
min-height: 100vh;}

Your jsx file sould have something like just to call it, using "className":

<div className="Login"><div>
Related