一、css实现
1、margin
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; } .div1{ height: 500px; background: #ff0000; overflow: hidden;/*解决外边距合并*/ } .div2{ width: 200px; height: 200px; background: #ffff00; margin:150px auto;/*设置宽才有用*/ } </style> </head> <body> <div class="div1"> <div class="div2"></div> </div> </body> </html>
2、定位+margin/translate(x,y)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; } .div1{ height: 500px; background: #ff0000; position: relative; } .div2{ width: 200px; height: 200px; background: #ffff00; position: absolute; left:50%;/**/ top:50%; /*margin-left:-100px;*/ /*margin-top:-100px;*/ /*知道宽高 配合position:absolute;left:50%;top:50%;使用*/ transform: translateX(-50%) translateY(-50%) ; /*不知道宽高时 配合position:absolute;left:50%;top:50%;使用*/ } </style> </head> <body> <div class="div1"> <div class="div2"></div> </div> </body> </html>
二、css3弹性盒模型实现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .parent{ width: 500px; height: 500px; background: #ff0000; display: -webkit-flex;/*配合使用*/ /*子元素水平对齐*/ -webkit-justify-content: center; /*子元素垂直对齐*/ -webkit-align-items: center; } .child{ width: 100px; height: 100px; background: #0f0; } </style> </head> <body> <div class="parent"> <div class="child"></div> </div> </body> </html>