Flexbox:屏幕中间的居中元素

Ven*_*soh 3 html css flexbox

如果我要使用flexbox在屏幕中间放置一个元素,这个代码最优雅吗?

http://codepen.io/vennsoh/pen/wEAmz

HTML

<div class='btn'></div>
Run Code Online (Sandbox Code Playgroud)

CSS

body{
  overflow: hidden;
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
}

.btn{
  width: 10rem;
  height: 10rem;
  background-color: #033649;
  margin: auto;
}
Run Code Online (Sandbox Code Playgroud)

似乎我必须使用position:absolute和height + weight 100%来实现这一点.

sha*_*han 18

你必须使用position:absolute,因为元素的默认值是position:relative,在这种情况下,没有什么是相对的,因为你已经将flex容器作为body.

您的代码可以正常工作,但是有一个命令可以在实际的flex模型中居中对象,如下所示:

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)*/
}
Run Code Online (Sandbox Code Playgroud)

如果你这样做,你可以从你的.btn类中删除margin:auto,或者在你的代码中提供更多的摆动空间.

是所有flexbox的好资源.