元素上下左右居中的几种方法

定位居中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; 
      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垂直+水平居中的四种方式,各有利弊。

posted @ 2017-10-01 16:50  chillylight  阅读(3235)  评论(0编辑  收藏  举报