如果我要使用 flexbox 将元素居中放置在屏幕中间,下面的方法是否最优雅?
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;
}
看来我必须使用position: absolute
和height+weight 100% 来实现这一点。
最佳答案
您必须使用 position: absolute,因为元素的默认位置是 position: relative,在这种情况下,没有什么是 relative to 因为您已经将 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)*/
}
如果您这样做,您可以从您的 .btn 类中删除 margin: auto,以便在您的代码中提供更多的回旋余地。
Here是所有关于 flexbox 的好资源。
关于html - Flexbox:在屏幕中间居中元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20451293/