Flexbox: Centering element in the middle of the screen
css, flexbox, html
Solution
You have to use position: absolute because the default for an element is position: relative, and in this case, there is nothing to be relative to because you have made the flex container the body.
Your code will work fine, but there is a command to center objects in the actual flex model itself like so:
body{
overflow: hidden;
position: absolute;
width: 100%;
height: 100%;
display: flex;
justify-content: center; /*centers items on the line (the x-axis by default)*/
align-items: center; /*centers items on the cross-axis (y by default)*/
}
If you do this you can remove the margin: auto from your .btn class to perhaps give some more wiggle room in your code.
Here is a good resource for all things flexbox.
Problem
If I'm going to center an element in the middle of the screen with flexbox, is the following approach the most elegant? HTML ``` <div class='btn'></div> ``` CSS ``` body{ overflow: hidden; position: absolute; width: 100%; height: 100%; display: flex; } .btn{ width: 10rem; height: 10rem; background-color: #033649; margin: auto; } ``` It seems that I have to use `position: absolute` and height+weight 100% to achieve this.