父级宽高不定,如何使子元素水平垂直居中?
下面是用 display: inline-block 实现的:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>垂直自适应</title> <style> * { margin: 0; padding: 0; } .box { position: relative; width: 400px; height: 600px; margin: 100px auto; border: 1px solid #666; text-align: center; } .content { width: 100px; height: 100px; display: inline-block; vertical-align: middle; background: red; } .middle-span { height: 100%; display: inline-block; vertical-align: middle; } </style> </head> <body> <div class="box"> <div class="content"></div> <span class="middle-span"></span> </div> </body> </html>
子级 display: inline-block; ,父级 text-align: center; ,实现水平居中。
子级 vertical-align: middle; ,且span height: 100%; ,实现垂直居中。