## 對元素垂直水平居中的幾種處理方法

~~~
<style>
.parent{
width: 200px;
height: 200px;
background-color: green;
}
.child{
width: 100px;
height: 100px;
background-color: red;
}
</style>
<div class="parent">
<div class="child"></div>
</div>
~~~
### 1.將父元素的display屬性設為flex
~~~
/*css樣式代碼:*/
.parent{
display: flex;
justify-content: center;/*該屬性在flex、float布局里有詳細說明*/
align-items: center;/*該屬性在flex、float布局里有詳細說明*/
}
~~~
### 2.分別給父元素和子元素相對定位與絕對定位
#### 2.1利用top、left、margin屬性進行調整
~~~
/*css樣式代碼:*/
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
~~~
#### 2.2利用top、left、transform屬性進行調整
~~~
/*css樣式代碼:*/
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
~~~
#### 2.3利用top、left、bottom、right屬性進行調整
~~~
/*css樣式代碼:*/
.parent{
position: relative;
}
.child{
position: absolute;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
~~~