盒子居中
阿新 • • 發佈:2018-07-03
gree 絕對定位 ctype utf-8 meta document osi oct code
1、標準流下元素居中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box { width: 100px; height: 100px; background-color: lightgreen; margin: 100px auto; } </style> </head> <body> <div class="box"></div> </body> </html>
2、position實現盒子居中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> body { position: relative; } .box { width: 100px; height: 100px; background-color: lightgreen; position: absolute; top: 100px; /* 移動了父元素寬度的一半* */ left: 50%; /* 移動了當前元素自己寬度一半 */ margin-left: -50px; } </style> </head> <body> <div class="box"></div> </body> </html>
3、通過位移的方式實現絕對定位的盒子居中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> body { position: relative; } .box { width: 100px; height: 100px; background-color: lightgreen; position: absolute; left: 50%; top: 100px; transform: translate(-50%,0); } </style> </head> <body> <div class="box"></div> </body> </html>
4、通過3D方式實現盒子居中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> body { position: relative; } .box { width: 100px; height: 100px; background-color: lightgreen; position: absolute; left: 50%; transform: translateX(-50%) translateY(100px); } </style> </head> <body> <div class="box"></div> </body> </html>
盒子居中