今天向一位朋友请教垂直水平居中问题,没想到朋友直接给出了三种实现方式,这里记录下来。
如图所示,登陆页中有一个登陆表单,我们需要将表单内容垂直水平居中。
这里,为了简单起见,以如下的html为例:
<div class='a1'>
<div class="a2">需要垂直水平居中的元素</div>
</div>
样式初始化
*{
margin:0;
padding:0;
}
html, body{
height: 100%;
}
最终我们想要实现的效果如下:
1. transform平移
这种方法利用css中的transform函数实现,好处在于通过百分比定位,具有很好的兼容性。
.a1{
width: 400px;
height:400px;
background-color:red;
position: relative; /* 父容器使用相对定位 */
}
.a2{
width:100px;
height: 200px;
background-color: orange;
position: absolute; /* 待垂直水平居中的子容器使用绝对定位 */
top:50%; /* 子容器顶部距离父容器50%的高度 */
left:50%; /* 子容器左边距离父容器50%的宽度 */
transform: translate(-50%,-50%); /* 子容器分别向上和向左移动其高度和宽度的一半的距离 */
}
2. calc动态计算子容器位置
这种方法利用css中的calc函数实现,该方式需要子容器的宽度和高度固定。
.a1{
width: 400px;
height:400px;
background-color:red;
position: relative; /* 父容器使用相对定位 */
}
.a2{
width:100px;
height: 200px;
background-color: orange;
position: absolute; /* 待垂直水平居中的子容器使用绝对定位 */
top:calc(50% - 100px); /* 利用calc函数计算子容器应当距离父容器顶部的距离(注意,这里“-”左边和右边需要有空格隔开) */
left:calc(50% - 50px); /* 利用calc函数计算子容器应当距离父容器左边的距离(注意,这里“-”左边和右边需要有空格隔开) */
}
3. flex布局
flex布局就是常说的弹性盒模型。利用html5中的flex布局也能实现垂直水平居中的效果。
#a1{
width: 200px;
height: 200px;
background-color: red;
display: flex; /* 父容器使用flex布局 */
justify-content: center; /* 设置子容器水平居中 */
align-items: center; /* 设置子容器垂直水平 */
}
#a2{
width: 50px;
height: 50px;
background-color: aqua;
}