盒子居中的几种方案。
No1:请看第一种方案。
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> *{ font-size: 1.875rem; } div:nth-child(1){ height: 200px; width: 300px; background-color:red; position: absolute; left: 50%; } div:nth-child(3){ height: 200px; width: 300px; background-color: lightcoral; position: absolute; left: 50%; margin-left: -100px; top: 50%; } div:nth-child(4){ height: 200px; width: 300px; background-color: deeppink; position: absolute; /*让div*/ /*left向left50% */ /*水平居中*/ left: 50%; margin-left: -100px; top: 50%; margin-bottom: 150px; } </style> <title>盒子居中问题</title> </head> <body> <div>0</div> <br> <div>1</div> </body> </html>
No2:请看第二种方案。
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> img { height: 200px; width: 300px; background-color: #FF99CC; position: absolute; left: 50%; margin-left: -100px; display: block; border: 3px solid red; border-radius: 20%; box-shadow: 6px 2px #000000; } </style> <title>盒子居中问题</title> </head> <body> <img src="img/bng/1.png" /> </body> </html>
No3:请看第三种方案。
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> div { height: 200px; width: 300px; background-color: lime; margin: auto; /*方案三*/ /* display: flex; justify-content: center; justify-items: center;*/ /*position: absolute;*/ /*left: 50%;*/ /*margin-left: -150px;*/ /*定位加margin*/ /* 方案四 position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto;*/ } </style> <title>盒子居中问题</title> </head> <body> <div></div> </body> </html>
No4:请看第四种方案。
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> div { height: 200px; width: 300px; background-color: red; position: absolute; left: 50%; margin-left: -150px; top: 50%; } </style> <title>盒子居中问题</title> </head> <body> <div></div> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> div { height: 200px; width: 300px; background-color: lightskyblue; position: absolute; left: 50%; margin-left: -150px; top: 50%; margin-top: -100px; } </style> <title>盒子居中问题</title> </head> <body> <div></div> </body> </html>
No5:请看第五种方案。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> div { background-color: lightskyblue; position: absolute; left: 50%; right: 50%; transform: translate(-50%, -50%); height: 200px; width: 300px; } </style> <title>盒子居中问题</title> </head> <body> <div></div> </body> </html>