-1

I'm trying to display a React Spinner component centered horizontally and vertically in the screen, after search and read different similar answers, for example this post, I could center it horizontally, currently my code is this:

import ClipLoader from "react-spinners/BounceLoader";

function Spinner() {
  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "row",
      }}
    >
      <ClipLoader color="#52bfd9" size={100} />
    </div>
  );
}

export default Spinner;

The result I'm getting is this:

center horizontally

However, I'm dealing how to center it vertically, the nearest I get from the solution is this code:

<div style={{ verticalAlign: 'middle', position:'absolute', top: '50%', left: '50%', marginTop: '-100px', marginLeft: '-250px' }}>

But it is not centered it vertically and horizontally, please take a look at the next image:

notcentered

My question is: do you have any recommendation how to center vertically and horizontally the div tag and the component?

htamayo
  • 335
  • 3
  • 16

3 Answers3

2

There are a few options to center the contents of a div. In your first example, you set the div to flex and set all of the alignment properties, but you're missing a height. By default the div is going to be height: auto;. So , it is centering the content vertically, but the div is the height of the item. Adding this css to your wrapping div should fix it:

height: 100vh;

You could also do this very easily with grid:

div {
    display: grid;
    height: 100vh;
    margin: 0;
    place-items: center;
}

Both of these do the same thing. You just need to add a height and you should be good to go.

davidleininger
  • 909
  • 4
  • 11
2

Someone beat me to it, but yeah your first approach is fine. You just need to specify the height for your flex container.

Demo/Example

https://codesandbox.io/s/centered-spinner-95874e

abgregs
  • 1,170
  • 1
  • 9
  • 17
1
<div
  className="spinner"
>
  <ClipLoader color="#52bfd9" size={100} />
</div>

and in your css file do this :

.spinner{
 height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
jozef koko
  • 82
  • 5