CSS居中方案
水平居中方案:
父元素text-align为center搭配子元素display:inline-block
<head> <style> .wrap { height: 200px; text-align: center; } .wrap div { display: inline-block; } </style> </head> <body> <div class="wrap"> <div>I am in middle</div> </div> </body>
子元素的display为table,搭配margin:0 auto实现,实质上利用了table的特性
<head> <style> .wrap { height: 200px; } .wrap div { display: table; margin:0 auto; } </style> </head> <body> <div class="wrap"> <div> 123 </div> </div> </body>
当子元素宽度已知时,使用margin:0 auto
<head> <style> .wrap { height: 200px; } .wrap div { width: 100px; margin:0 auto; } </style> </head> <body> <div class="wrap"> <div> 123 </div> </div> </body>
利用Position定位结合Transform(css3)
<head> <style> .wrap { height: 200px; text-align: center; position: relative; } .wrap div { position: absolute; left: 50%; transform: translateX(-50%); } </style> </head> <body> <div class="wrap"> <div>I am in middle</div> </div> </body>
垂直居中解决方案
绝对居中
<head> <style> .wrap { height: 400px; position: relative; } .inner { height: 200px; width: 200px; margin: auto; position: absolute; top: 0; left: 0; right: 0; bottom: 0; } </style> </head> <body> <div class="wrap"> <div class="inner"> 123 </div> </div> </body>
利用Tranform
<head> <style> .wrap { height: 400px; position: relative; } .inner { height: 200px; width: 200px; margin: auto; position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%); } </style> </head> <body> <div class="wrap"> <div class="inner"> 123 </div> </div> </body>
单行inline
<head> <style> .wrap { height: 400px; position: relative; } .inner { height: 400px; width: 200px; line-height: 400px; text-align: center; margin:0 auto; } </style> </head> <body> <div class="wrap"> <div class="inner"> 123 </div> </div> </body>