css控制div上下左右居中
1、代码复制可直接看到效果。
有三种效果:
div上下左右都居中(table-cell)
div左右居中(text-align)
span文字上下左右居中(line-height)
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <style> .parentDiv{display: table-cell;vertical-align: middle; width: 200px;height: 100px;background-color: #0000ff; } .childDiv{width: 100px;height: 50px;background-color: #ffff00;margin: 0 auto;} .parentDiv1{text-align: center; width: 200px;height: 100px;background-color: #0000ff; } .childDiv1{width: 100px;height: 50px;background-color: #ffff00;margin: 0 auto;} .parentDiv2{text-align: center;height: 40px; width: 90px;background-color: #0000ff; } .childDiv2{margin: 0 auto;line-height: 40px;background-color: #ffff00;} </style> </head> <body> <div class="parentDiv"> <div class="childDiv">垂直,左右居中</div> </div> <br> <div class="parentDiv1"> <div class="childDiv1">左右居中</div> </div> <br> <div class="parentDiv2"> <span class="childDiv2">文字居中</span> </div> </body> </html>