下面是水平和垂直居中的方法:
1.Flex 方案
2.Grid 方案
3.absolute + transform
4.absolute + 負(fù) margin
5.absolute + margin: auto
Flex 方案
justify-content,align-items
代碼鏈接:http://js.jirengu.com/gasekameza/9/edit?html,css,output
flex+margin:auto
代碼鏈接:http://js.jirengu.com/gasekameza/10/edit?html,css,output
目前在移動(dòng)端已經(jīng)完全可以使用 Flex 布局了歌逢,PC 端需要看自己業(yè)務(wù)的兼容性情況。
優(yōu)點(diǎn):不需要固定居中元素的寬高。
兼容性:
IE 10+, Chrome 4+, Firefox 2+
Android 2.3+, iOS 6+
Grid 方案
justify-content,align-items
代碼鏈接:http://js.jirengu.com/gasekameza/12/edit?html,css,output
grid+margin:auto
代碼鏈接:http://js.jirengu.com/gasekameza/11/edit?html,css,output
優(yōu)點(diǎn):不需要固定居中元素的寬高。
兼容性:
IE 10+, Chrome 57+, Firefox 52+
Android 6+, iOS 10.3+
absolute + transform
CSS3 中新增的 transform,其 translate 屬性是根據(jù)元素自身計(jì)算的畜眨。例如:設(shè)置 transform: translateX(-50%);,元素會(huì)向左偏移自身寬度的一半文狱。根據(jù)這一特性圈暗,很容易實(shí)現(xiàn)元素的居中掂为。
代碼鏈接:http://js.jirengu.com/gasekameza/14/edit?html,css,output
優(yōu)點(diǎn):不需要固定居中元素的寬高。
absolute + 負(fù) margin
代碼鏈接:http://js.jirengu.com/zezutemika/1/edit?html,css,output
缺點(diǎn):需要固定居中元素的寬高员串。
兼容性:
IE 6+, Chrome 4+, Firefox 2+
Android 2.3+, iOS 6+
absolute + margin: auto
代碼鏈接:http://js.jirengu.com/ficutujada/1/edit?html,css,output
缺點(diǎn):需要固定居中元素的寬高勇哗,否則其寬高會(huì)被設(shè)為 100%
兼容性:
IE 6+, Chrome 4+, Firefox 2+
Android 2.3+, iOS 6+