1. 程式人生 > 其它 >讓盒子居中的幾種常用的方式~

讓盒子居中的幾種常用的方式~

結構:

<div class="wrapper">
	<div class="box"></div>
 </div>

樣式一,也是最傳統的方法,使用定位,需要知道自身的寬高:

.wrapper{
 	position: relative;
 	width: 400px;
 	height: 400px;
 	background-color: aqua;	
 }
 .box{
 	position: absolute;
 	width: 100px;
 	height: 100px;
 	background-color: red;
 	left: 50%;
 	top:50%;
 	margin-left: -50px;
 	margin-top: -50px;
 }

樣式二,使用定位,使用css3新特效translate:

.wrapper{
   	position: relative;
   	width: 400px;
   	height: 400px;
   	background-color: aqua;	
  }
 .box{
  	position: absolute;
  	width: 100px;
  	height: 100px;
  	background-color: red;
  	left: 50%;
  	top:50%;
  	transform: translate(-50%,-50%);
  }

樣式三,利用flex(彈性佈局):

.wrapper{
   	display: flex;
   	width: 400px;
   	height: 400px;
   	background-color: aqua;	
   	justify-content: center;
   	align-items: center;
 }
 .box{
 	width: 100px;
 	height: 100px;
    background-color: red;	
 }

樣式四,使用定位,可以不知道自身寬高,但是你設定的時候必須要有寬高:

 .wrapper{
 	display: flex;
 	width: 200px;
 	height: 400px;
 	background-color: aqua;	
 	position: relative;
 }
 .box{
 	width: 100px;
 	height: 100px;
 	background-color: red;	
 	position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
 }

樣式五,利用justify-content:space-around;(用的極少)

.wrapper{
 	display: flex;
 	width: 400px;
 	height: 400px;
 	background-color: aqua;	
 	/*justify-content: space-between;  (左右兩邊對齊)*/
 	justify-content: space-around;
 	align-items: center;
 }
 .box{
 	width: 100px;
 	height: 100px;
 	background-color: red;	
 }

樣式六,利用display: table-cell; vertical-align: middle:

 .wrapper{
 	display: flex;
 	width: 400px;
 	height: 400px;
 	background-color: aqua;	
    display: table-cell;
    vertical-align: middle;
 }
 .box{
 	width: 100px;
 	height: 100px;
 	background-color: red;	
    margin: auto;
 }
方式。。。。。。。。。。。。。。。。

flex擴充套件:
justify-content: center; 水平居中
justify-content: space-between; 兩端對齊
justify-content: space-around; 盒子四周距離相等(可以用來居中)
justify-content: flex-start; 左端對齊
justify-content: flex-end; 右端對齊