一、在需要居中的元素加上如下C3属性即可:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .div{ height: 330px; width: 330px; background-color: mediumspringgreen; border: 6px solid lightcoral; text-align: center; line-height: 330px; position: absolute; top: 50%; left: 50%; -webkit-transform: translateX(-50%) translateY(-50%); -moz-transform: translateX(-50%) translateY(-50%); -ms-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); } </style> </head> <body> <div class="div">上下左右居中</div> </body> </html>
二、只要在父级元素上面加上这三句话就可以实现不定宽高水平垂直居中:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .father{ width: 900px; height: 900px; background-color: aqua; display:flex; justify-content:center;/*水平居中*/ align-items:center;/*垂直居中*/ } .div{ height: 330px; width: 330px; background-color: mediumspringgreen; border: 6px solid lightcoral; text-align: center; line-height: 330px; /*position: fixed;*/ /*top: 50%;*/ /*left: 50%;*/ /*-webkit-transform: translateX(-50%) translateY(-50%);*/ /*-moz-transform: translateX(-50%) translateY(-50%);*/ /*-ms-transform: translateX(-50%) translateY(-50%);*/ /*transform: translateX(-50%) translateY(-50%);*/ } </style> </head> <body> <div class="father"> <div class="div">上下左右居中</div> </div> </body> </html>