## 居中
**示例鏈接:** http://www.lsxm.tech/doc/demo/center.html
>[success]### 一、水平居中
#### 1、塊狀元素水平居中
**width: 150px;
margin:0 auto;**
<div style="width: 150px;margin:0 auto;background:red">margin:0 auto;</div>
即通過左右外邊距自動(auto)來實現水平居中. (需要設置寬度)
#### 2、內聯元素水平居中
**text-align:center;**
設置父div為text-align:center;讓div里的塊狀元素水平居中
<div style="text-align:center;background:red"><span>text-align:center;</span></div>
#### 3、定位水平居中
**position: absolute;
left:50%;
width: 100px;
margin-left:-50px;寬度的一半**
通過絕對定位(fixed也行),設置left為:50%;最后向左偏移寬度的一半來抵消div以左邊框定位所產生的偏移。
<div style="position:relative;height:200px;background:green">
<div style="position:absolute;left:50%;top:0;width:200px;margin-left:-100px;background:red">
position: absolute;<br>
left:50%;<br>
width: 100px;<br>
margin-left:-50px;
</div>
</div>
>[info]### 二、垂直居中
#### 1、內聯元素垂直居中line-height=height
**height: 100px;
line-height: 100px;**
<div style="height:100px;line-height:100px;background:red">
margin:0 auto;
</div>
#### 2、定位垂直居中
**position: absolute;
top:50%;
height: 100px;
margin-top:-50px;高度的一半**
<div style="position:relative;height:200px;background:green">
<div style="position:absolute;left:50%;top:50%;width:200px;height:120px;margin-left:-100px;margin-top:-60px;text-align:center;background:red">
position: absolute;<br>
top:50%;<br>
width: 100px;<br>
margin-top:-50px;
</div>
</div>
#### 3 、js計算居中
絕對定位,用js計算left、top。如
left:(父width-子width)/2
top:(父height-父height)/2
通常用于父子元素高度、寬度不確定或產生變動的情況下。