如何实现固定宽高的DOM元素的水平垂直居中
效果:
实现代码1:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> body{margin: 0; padding: 0;} #div1{ margin-top: 100px; margin-left: 150px; width: 300px; height: 300px; background-color: red; position: relative; } #div2{ width: 120px; height: 120px; background-color: black; position: absolute; /*(300-120)/2/300*/ top: 30%; left: 30%; } </style> </head> <body> <div id="div1" class="classname"> <div id="div2" class="classname"> </div> </div> </body> </html>
实现代码2:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> body{margin: 0; padding: 0;} #div1{ margin-top: 100px; margin-left: 150px; width: 300px; height: 300px; background-color: red; } #div2{ width: 120px; height: 120px; background-color: black; /*(300-120)/2/300=30%*/ position: relative; top: 30%; left: 30%; } </style> </head> <body> <div id="div1" class="classname"> <div id="div2" class="classname"> </div> </div> </body> </html>
实现代码3: