If I am going to center an element in the middle of the screen with flexbox, is this code most elegant?
http://codepen.io/vennsoh/pen/wEAmz
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With