水平居中
- 如果是行內元素,要實現水平居中只需要將父元素設置為text-align=center
- 如果是固定寬度的塊狀元素,設置該元素本身為margin: 0 auto
- css3的新屬性font-content,自動將元素寬度縮小到內容的寬度,然后使用margin:0 auto可以輕松的實現水平居中(目前只支持chrome和FireFox)
.son{ width: -moz-fit-content; width: -webkit-fit-content; width:fit-content; margin:0 auto; }
4.絕對定位以及margin-left的負值實現水平居中
.son { position: absolute; width: 50px; left: 50%; margin-left: -25px;(寬度的一半) background-color: blue; text-align: center; }
5.絕對定位left right同時設置為0 同時設置margin:0 auto
.son{ position: absolute; width: 50px; left: 0; right: 0; background-color: blue; margin: 0 auto; height: 100%; }
垂直居中
- 若元素為單行文本,直接設置其text-align為父元素的高度
- 利用position以及top bottom屬性
.son{ position:absolute; height:固定; top:0; bottom:0; margin:auto 0; }
3.利用margin的負值
.son{ position:absolute; top:50%; height:固定; margin-top:-0.5高度; }
4.利用vertical-align
.parent::after, .son{ display:inline-block; vertical-align:middle; } .parent::after{ content:''; height:100%; }