给父元素设置position:relative,自己设置position: absolute属性
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>使得一个div元素居中显示</title> 5 <style type="text/css"> 6 .box{width: 500px;height:500px;background-color:green}
.container{width:100px;height:100px;background-color:red} 7 8 </style> 9 </head> 10 <body> 11 <div class="box" > 12 <div class="container"></div> 13 </div> 14 </body> 15 </html>
<!DOCTYPE html> <html> <head> <title>使得一个div元素居中显示</title> <style type="text/css"> .box{width:500px;height:500px;background-color:green;position:relative} .container{width: 100px;height: 200px;background-color:red;position:absolute;margin:auto;left:0;right:0;top:0;bottom:0} </style> </head> <body> <div class="box" > <div class="container"></div> </div> </body> </html>
给父元素添加position:relative;自己设置position:absolute, margin的值设置负值
<!DOCTYPE html> <html> <head> <title>使得一个div元素居中显示</title> <style type="text/css"> .box{width:500px;height:500px;background-color:green;position:relative} .container{width: 100px;height: 200px;background-color:red;position:absolute;left:50%;top:50%; margin-top:-100px;margin-left:-50px;} </style> </head> <body> <div class="box" > <div class="container"></div> </div> </body> </html>
display:flex
<!DOCTYPE html> <html> <head> <title>使得一个div元素居中显示</title> <style type="text/css"> .box{width:500px;height:500px;background-color:green;display: flex;justify-content:center;align-items: center} .container{width: 100px;height: 200px;background-color:red} </style> </head> <body> <div class="box" > <div class="container"></div> </div> </body> </html>