垂直居中
方案一 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; display: table-cell;/* 子元素child就变成了一个单元格 */ vertical-align: middle;/* 子元素垂直居中 */ } .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; position: absolute; top: 50%; transform: translateY(-50%); } </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:center;/* 只设置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>
开始做,坚持做,重复做