方案一 table-cell vertical-align
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>垂直居中 table-cell vertical-align</title> <link rel="stylesheet" type="text/css" href="../../reset.css"> <style type="text/css"> .parent{ background: #bebebe; width: 50px; height: 200px; 元格 */ * 子元素垂直居中 */ } .child{ background: #404040; color:white; width: 50px; height: 50px; } </style> </head> <body> <div class="parent"> <div class="child">DEMO</div> </div> </body> </html>
方案二 垂直居中absolute_transform
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>垂直居中absolute_transform</title> <style type="text/css"> .parent{ background: #404040; height: 300px; width: 50px; position: relative; } .child{ background: #bebebe; height: 50px; width: 50px; } </style> </head> <body> <div class="parent"> <div class="child">DEMO</div> </div> </body> </html>
方案三 垂直居中flex_align-items
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>垂直居中flex_align-items</title> <style type="text/css"> .parent{ background: #bebebe; height: 300px; width: 50px; ;/* 只设置display:flex时, align-items默认为 stretch 即拉伸,*/ } .child{ background: #404040; /*height: 50px;*/ width: 50px; color: white; } </style> </head> <body> <div class="parent"> <div class="child">DEMO</div> </div> </body> </html>