1. 程式人生 > 實用技巧 >css水平垂直居中幾種方法?

css水平垂直居中幾種方法?

首先我們規定兩個div,為父子級別,後面各個案例都是基於

1 <div class="parent">
2     <div class="child">
3         demo
4     </div>
5  </div>

一、最簡單的居中 margin:0 auto,上程式碼

 1 .parent {
 2    width: 200px;
 3    height: 200px;
 4    background-color: crimson;
 5 }
 6 
 7 .child {
 8    width: 100px;
 9    height
: 100px; 10 margin: 0 auto; 11 text-align: center; 12 line-height: 100px; 13 background-color: orange; 14 }

二、第二種也是利用margin屬性設定left,top,需要設定父級position:relative;子級position:absolute;

 1 .parent {
 2    position: relative;
 3    width: 200px;
 4    height: 200px;
 5    background-color: crimson;
 6
} 7 8 .child { 9 position: absolute; 10 width: 100px; 11 height: 100px; 12 background-color: orange; 13 left: 50%; 14 top: 50%; 15 margin: -50px 0 0 -50px; 16 }

三、利用transform的平移方法translate,同樣要設定position

 1 .parent {
 2    position: relative;
 3    width: 200px;
 4    height: 200px;
 5    background-color
: crimson; 6 } 7 8 .child { 9 position: absolute; 10 width: 110px; 11 height: 110px; 12 background-color: orange; 13 left: 50%; 14 top: 50%; 15 transform: translate(-50%, -50%); 16 }

四、利用flex佈局,設定父級justify-content和align-items,或者設定父級的justify-content和子級align-self屬性都可以達到效果

 1 .parent {
 2    width: 200px;
 3    height: 200px;
 4    background-color: crimson;
 5    display: flex;
 6    justify-content: center;
 7    align-items: center;
 8 }
 9 
10 .child {
11    width: 100px;
12    height: 100px;
13    background-color: orange;
14 }

or

 1 .parent {
 2    width: 200px;
 3    height: 200px;
 4    background-color: crimson;
 5    display: flex;
 6    justify-content: center;
 7 }
 8 
 9 .child {
10    width: 100px;
11    height: 100px;
12    background-color: orange;
13    align-self: center;
14 }

五、利用left,top,bottom,right設定相等的值,不一定為0,加上margin:0

 1 .parent {
 2    position: relative;
 3    width: 200px;
 4    height: 200px;
 5    background-color: crimson;
 6 }
 7 
 8 .child {
 9    position: absolute;
10    width: 100px;
11    height: 100px;
12    background-color: orange;
13    left: 0;
14    right: 0;
15    top: 0;
16    bottom: 0;
17    margin: auto;
18 }

六、利用inline-block的vertical-align:middle去對齊偽元素

 1 .parent {
 2    width: 200px;
 3    height: 200px;
 4    background-color: crimson;
 5    text-align: center;
 6    overflow: auto;
 7 }
 8 
 9 .parent::after {
10    content: '';
11    display: inline-block;
12    vertical-align: middle;
13    height: 100%;
14    margin-left: -0.25em;
15 }
16 
17 .child {
18    width: 100px;
19    height: 100px;
20    background-color: orange;
21    display: inline-block;
22    vertical-align: middle;
23 }

待完善