Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox: Centering element in the middle of the screen

Tags:

html

css

flexbox

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.

like image 360
Vennsoh Avatar asked Dec 08 '13 08:12

Vennsoh


1 Answers

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.

like image 96
shan Avatar answered Sep 30 '22 00:09

shan