Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vertically and horizontally center a component in react?

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%)'
      }} />);
    }
like image 983
James L. Avatar asked Sep 11 '18 21:09

James L.


4 Answers

Another option is to use flex-box.

<div style={{
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
}}>
    Hello world
</div>
like image 138
asdf1234 Avatar answered Oct 21 '22 06:10

asdf1234


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.

like image 27
Marcel Avatar answered Oct 21 '22 07:10

Marcel


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).

like image 2
James L. Avatar answered Oct 21 '22 06:10

James L.


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,
  }} />);
}
like image 1
Justin Meskan Avatar answered Oct 21 '22 07:10

Justin Meskan