CSS实现垂直水平居中
1. 使用绝对定位和相对定位,父元素相对定位,要垂直居中的元素绝对定位,设置 left,right,top,bottom为0
demo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CSS实现垂直水平居中</title> <style type="text/css"> *{ margin:0; padding:0; } .main { position:relative; width:200px; height:200px; border:1px solid darkred; } .content { /*子元素为绝对定位*/ position:absolute; width:100px; height:100px; right:0; left:0; top:0; bottom:0; /*margin设置为auto*/ margin :auto ; border:1px solid blueviolet; } </style> </head> <body> <div class="main"> <div class="content"></div> </div> </body> </html>
效果:
2. 使用flex布局
demo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CSS实现垂直水平居中</title> <style type="text/css"> *{ margin:0; padding:0; } .main { /*flex 布局*/ display: flex; /*实现垂直居中*/ align-items:center ; /*实现水平居中*/ justify-content:center; width:200px; height:200px; border:1px solid yellow; } .content { width:100px; height:100px;
border:1px solid blueviolet; } </style> </head> <body> <div class="main"> <div class="content"></div> </div> </body> </html>
效果:
3.
使用 cell-table布局
demo
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>CSS水平垂直居中实现方式--定位实现</title> <style type="text/css"> *{ margin: 0; padding: 0; } .p{ width: 250px; height: 250px; border: 1px solid red; display: table-cell; /*vertical-align: middle; 实现垂直居中*/ vertical-align: middle; } .c{ width: 100px; height: 100px; border: 1px solid green; /*margin: 0 auto; 实现水平居中*/ margin: 0 auto; } </style> </head> <body> <div class="p"> <div class="c"> 子元素 </div> </div> </body> </html>
效果:
2018-03-21 01:37:25
越努力越幸运