以下是实现未知宽高元素水平垂直居中的三个方法:
方法1:通过定位和transform属性来实现
html:
实现未知宽高元素垂直居中的方法1:通过定位和transform来实现
<style>
.parent{
width:100%;
height:400px;
background:#666;
position:relative;
}
.children{
position:absolute;
top:50%;
left:50%;
background:red;
transform:translate(-50%,-50%);
}
</style>
方法2:通过利用flex布局
html:
实现未知宽高元素的水平垂直居中方法2:主要是利用flex布局来实现
<style>
.parent{
width:100%;
height:400px;
background:#666;
display:flex;
align-items:center;
justify-content:center;
}
.children{
background:red;
}
</style>
方法3:通过table属性
html:
实现未知宽高元素垂直水平居中,主要原理是将父元素设置为table,子元素设置为table-cell,利用table属性
<style>
.parent{
display:table;
width:100%;
height:400px;
background:#666;
}
.children{
display:table-cell;
vertical-align:middle;
text-align:center;
background:red;
}
</style>
原文:https://blog.youkuaiyun.com/tozeroblog/article/details/79943579