Flexbox: Centering element in the middle of the screen

Viewed 34648

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.

2 Answers

You can position an element inside a container by using place-items without the need to add any CSS property to that element. In this case I'm using the body of document as the container.

Snippet

body{
  margin:0;
  height:100vh; /* use 100% of the height of the viewport */
  display:grid;             
  place-items: center;
}
<body>
  <button>I'm a lonely button :B</button>
</body>

About place-items

The CSS place-items shorthand property allows you to align items along both the block and inline directions at once (i.e. the align-items and justify-items properties) in a relevant layout system such as Grid or Flexbox. If the second value is not set, the first value is also used for it.

Find more info here

Related