积少成多,聚水成涓!css
父元素高度肯定的单行文本设置 height=line-heightcss3
body { background: black; } .c2 { height: 80px; line-height: 80px; width: 80px; text-align: center; background: red; } <body> <div class="block"> 123123 </div> </body>
只是单行文本水平垂直居中,块级元素并无web
使用position:absolute,设置 left、top、margin-left、margin-topspa
.c1 { height: 300px; width: 300px; background: black; position: relative; } .c2 { height: 200px; width: 200px; position: absolute; left: 50%; top: 50%; margin-top: -100px; margin-left: -100px; background: red; } <div class="c1"> <div class="c2"> </div> </div>
特色:兼容性好,不过需固定宽高
注意:若是不设置c1 position为relative,则c2将基于根元素定位居中3d
position:absolute,同时设置top/bottom/right/leftcode
body { background: black; } .block { height: 200px; width: 200px; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; background: red; }
特色: 可不用设置高宽,且兼容性好orm
使用position:fixed,一样设置left、top、margin-left、margin-top的属性blog
body { background: black; } .block { height: 200px; width: 200px; position: fixed; left: 50%; top: 50%; margin-top: -100px; margin-left: -100px; background: red; } <body> <div class="block"> </div> </body>
特色:position:fixed; IE 不支持,且需固定宽高ip
设置position:fixed ,同时设置left/right/top/bottom为0,margin:autoit
body { background: black; } .block { height: 200px; width: 200px; position: fixed; left: 0; right: 0; top: 0; bottom: 0; margin: auto; background: red; } <body> <div class="block"> </div> </body>
特色: position:fixed IE 不支持,不过不需固定宽高
display:table-cell属性使内容垂直居中
body { background: black; } .block { height: 200px; width: 200px; display: table-cell; vertical-align: middle; text-align: center; background: red; } <body> <div class="block"> 123123 </div> </body>
特色:使内容居中,块级元素不能居中
使用css3的display:-webkit-box属性,再设置-webkit-box-pack:center/-webkit-box-align:center
body { display: -webkit-box; -webkit-box-pack: center; -webkit-box-align: center; background: black; } .block { height: 200px; width: 200px; color: yellow; display: -webkit-box; -webkit-box-pack: center; -webkit-box-align: center; background: red; } <body> <div class="block"> <span>123123</span> </div> </body>
特色: 无需定宽高,行内和块级元素均可水平垂直居中!但CSS3 IE 兼容性要考虑
body { background: black; } .block { height: 200px; width: 200px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); background: red; } <body> <div class="block"> <span>123123</span> </div> </body>
特色: 无需固定宽高但只能使块级元素水平垂直居中!但CSS3 在 IE 兼容性须要考虑