css中div垂直居中的方法。
利用绝对定位实现的居中
代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>居中</title> <style type="text/css"> *{ padding: 0px; margin: 0px; } body { height: 100%; overflow: hidden; } .father{ position: absolute; height: 500px; width: 100%; background-color:#2AABD2; } .children{ position: absolute; top: 50%; left: 50%; background-color: red; width: 100px; height: 100px; margin: -50px 0 0 -50px; } </style> </head> <body> <div class="father"> <div class="children"> </div> </div> </body> </html>
效果图如下:
利用flex垂直居中
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>居中</title> <style type="text/css"> *{ padding: 0px; margin: 0px; } body { height: 100%; overflow: hidden; } .father{ height: 500px; width: 100%; background-color:#2AABD2; display: flex; justify-content: center;/*实现水平居中*/ align-items:center; /*实现垂直居中*/ } .children{ background-color: red; width: 100px; height: 100px; } </style> </head> <body> <div class="father"> <div class="children"> </div> </div> </body> </html>
效果图如下:
transform+relative实现的居中
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>居中</title> <style type="text/css"> *{ padding: 0px; margin: 0px; } body { height: 100%; overflow: hidden; } .father{ position: absolute; height: 500px; width: 100%; background-color:#2AABD2; } .children { width: 300px; height: 150px; background-color: #333333; position: relative; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%); } </style> </head> <body> <div class="father"> <div class="children"> </div> </div> </body> </html>
效果图如下:
多谢@alexxxcs1提供的另一种方式(不晓得这样能否@到^_^),嘛其实网上实现居中的方式确实很多,互相探讨加深印象。
相关推荐
/*垂直居中,div上边界距离窗口上边的距离为窗口高度的50%,并针对不同浏览器进行兼容。-- 在外层添加一个div,把行内容居中,添加.row .justify-content-center -->
Phoebe的学习天地 2020-04-14
STPace 2020-02-17
Simagle 2015-05-27
Dorissun 2016-09-22
ThikHome 2015-05-27
impress 2019-07-01
linfei0 2015-02-01
AnyBisks 2013-07-02
云端漂移 2013-03-20
CoderChang 2012-11-20
统一开发环境UDE 2012-08-31
teresalxm 2011-08-16
xtuhcy 2011-05-11
lovehuayud 2011-04-06
tivon仔 2010-09-10
Ladyseven 2010-09-07
林一天 2010-09-01
Ladyseven 2010-08-31