在平时,我们经常会遇到让一个div框针对某个模板上下左右都居中(水平垂直居中),其实针对这种情况,我们有很多种方法实现。
方法一:
绝对定位法,不确定当前div宽度和高度,采用 transform: translate(-50%,-50%);,当前div的父级添加相对定位(position: relative;)
效果图:
.one{
width: 200px;
height: 200px;
background: #4a5064;
position: relative;
}
.two{
width: 100px;
height: 100px;
background: #007aff;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);//与方法二不同处
}
方法二:
绝对定位的方法:确定要居中的div宽度,margin值为要居中div宽度一半的负值。
代码如下:
.one{
width: 200px;
height: 200px;
background: #4a5064;
position: relative;
}
.two{
width: 100px;
height: 100px;
background: #007aff;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;//与方法一不同处
margin-top: -50px;//与方法一不同处
}
方法三:
绝对定位的方法:绝对定位下top、left、reign、bottom 都设置为0。
代码如下:
.one{
width: 200px;
height: 200px;
background: #4a5064;
position: relative;
}
.two{
width: 100px;
height: 100px;
background: #007aff;
position: absolute;
left: 0;//代码不同处
right: 0;//代码不同处
top: 0;//代码不同处
bottom: 0;//代码不同处
margin: auto;//代码不同处
}
方法四:
flex布局方法:当前div的父级添加flex css样式。
代码如下:
.one{
width: 200px;
height: 200px;
background: #4a5064;
display: flex;
align-items: center;
justify-content: center;
-webkit-display:flex;//兼容safari浏览器
-webkit-align-items: center;//兼容safari浏览器
-webkit-justify-content: center;//兼容safari浏览器
}
.two{
width: 100px;
height: 100px;
background: #007aff;
}
方法五:
table-cell实现水平垂直居中:table-cell middle center 结合使用。垂直居中的如果是div 等块级元素,需设置display: inline-block;
代码如下:
.one{
width: 200px;
height: 200px;
background: #4a5064;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.two{
width: 100px;
height: 100px;
background: #007aff;
display: inline-block;
}
方法六:
绝对定位:calc( ) 函数动态计算水平居中。
代码如下:
.one{
position: relative;
width: 200px;
height: 200px;
background: #4a5064;
}
.two{
position: absolute;
width: 100px;
height: 100px;
background: #007aff;
left: -webkit-calc((200px - 100px)/2);//兼容chrome、safari
top: -webkit-calc((200px - 100px)/2);//兼容chrome、safari
left: calc((200px - 100px)/2);//重点 减号 两边要有空格!!!!!!
top:calc((200px - 100px)/2) ;
left: -moz-calc((200px - 100px)/2);//兼容火狐浏览器
top: -moz-calc((200px - 100px)/2);//兼容火狐浏览器
}