如何将一个未知高度的元素垂直居中,通常有两种常用的方法:
//html <div > <div >center</div> </div>
1、用绝对定位和translate
.parent{
height: 300px;
width: 300px;
position: relative;
background-color: bisque;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
padding: 30px;
background-color: cornflowerblue;
}
2、基于 Flexbox 的解决方案
这是毋庸置疑的最佳解决方案,因为 Flexbox 是专门针对这类需求所设计的,只是一些老的浏览器版本兼容性可能不是很好,具体可以查看caniuse,现代浏览器一般没问题。
.parent{
height: 300px;
width: 300px;
background-color: bisque;
display: flex;
justify-content: center;
align-items: center;
}
.child{
padding: 30px;
background-color: cornflowerblue;
}
