<div class="one"></div>
.one{ position: absolute; width: 200px; height: 200px; top: 50%; left: 50%; margin-left: -100px; margin-right: -100px; background: green; }
優勢:
基本瀏覽器都能兼容css
缺點:
必需要固定寬高css3
<div class="two"></div>
.two{ position: absolute; width: 100px; height:100px; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }
以上兩種方法均可以把absolute換成fixed,注意,fixed在ie下不支持瀏覽器
<div class="inner"> <div class="foo"></div> </div>
.inner{ width: 100px; height: 100px; display: table-cell; text-align: center; vertical-align: middle; } .foo{ display: inline-block; width: 50%; height: 50%; }
設置了table-cell以後,父元素就變成了一個單元格
關於使用table-cee佈局bash
<div class="four"> 內容居中 </div>
.four{ width: 100px; height: 100px; line-height: 100px; text-align: center; }
這種方法只能居中行內元素。經常使用於文字對其居中佈局
<div class="five"></div>
.five{ position: absolute; top: 50%; height: 50%; transform: translate(-50%, -50%); }
好處就是不可不用定義寬高,可是對於不兼容css3的瀏覽器沒有做用flex
<div class="six"> <div class="content"></div> </div>
.six{ position:aabsolute; left: 0; right: 0; top: 0; bottom: 0; text-align: center; } .six:before{ content: ''; display: inline-block; vertical-align: middle; height: 100%; } .six .content{ display: inline-block; vertical-align: middle; width: 40px; height: 40px; line-height: 40px; }
<div class="eight"> <div class="content"></div> </div>
.eight{ display: flex; align-items: center; justify-content: center; }
一樣,會存在瀏覽器兼容問題code