元素上下左右居中的⼏种⽅法
定位居中1:relative,left top 50%,负margin-left margin-top
让外层div相对定位(得设置宽⾼),内层div绝对定位,top、left分别设为50%,然后通过设置margin-top、margin-left值为宽度的负数并且是内层div的⼀半,就可以成功实现垂直⽔平居中了。如下:
<style>
.one{
position: relative;
width: 100%;
height: 500px;
}
.two{
position: absolute;
left: 50%;
top:50%;
margin-left: -100px;
margin-top: -100px;
background-color: #a00;
width: 200px;
height: 200px;
}
</style>
<div class="one">
<div class="two"></div>
</div>
定位居中2:absolute,margin: auto
与1类似,不过将two的定位稍作修改,不⽤算什么百分⽐,margin什么的,原理就是让two既要往左也要往右,既要往上也要往下。这时候它就不知所措了,只好待在中间。:
.two{
position: absolute;
css设置文字垂直居中
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: #a00;
width: 200px;
height: 200px;
}
这个⽅法,不仅能在内部宽度不确定时发挥作⽤,还能兼容各种主流浏览器,看上去似乎很完美,但事实上,当我们的需求改为:宽度随内部⽂字⾃适应,即宽度未设置时,这种⽅法就⽆法满⾜需求了,原因是left、right设为0后,inner在宽度未设置时将占满⽗元素的宽度。
定位居中3:relative,left top 50%,transform: translate(-50%,-50%)
居中的主要⽬的是让⾥⾯的div在top和left⽅向发⽣50%偏移之后,再往回偏移⼀定距离,⽽在css3中新增的属性,selector{transform:translate();}也可实现这个功能。translate代表着⽔平、垂直⽅向上的转换(位移),其中当括号内的值设为百分⽐时,将以元素⾃⾝宽度为基准,移位相应的宽度,显然设为-50%就可以实现我们想要的效果。
将⾥⾯的div样式修改如下:
.two{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: #a00;
width: 200px;
height: 200px;
}
这个⽅法妥善解决了内层div宽度不确定的问题,不⽤像第⼀种⽅法⼀样计算应该向左向上偏移多少了,但由于使⽤了css3的新属性,在低版本ie浏览器下是不兼容的。
定位居中4:flex
运⽤flex布局,flex布局是移动端⼀种很新潮的布局⽅法,利⽤flex布局使元素垂直⽔平居中,缺点依然是令⼈头疼的兼容性问题(在ie11-中不起作⽤),优点是代码量⽐前⼏种⽅法相⽐略少,⽅便使⽤。
<style>
.one{
margin:0 auto;
width: 100%;
height: 500px;
display: flex;/*设置外层盒⼦display为flex*/
justify-content:center;/*设置内层盒⼦的⽔平居中*/
align-items:center;/*设置内层盒⼦的垂直居中*/
}
.two{
display: inline-block;
background-color: #a00;
width: 200px;
height: 200px;
}
</style>
<body>
<div class="one">
<div class="two">我们都是好孩⼦</div>
</div>
</body>
以上就是使div垂直+⽔平居中的四种⽅式,各有利弊。