盒子內容垂直居中
阿新 • • 發佈:2018-12-21
盒子內容垂直居中有兩種:
1.給父級加上相對定位position:relative; 給子元素新增絕對定位position:absolute;
設定top,right,bottom,left的值都是0;調整margin內邊距為自適應auto;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> *{margin: 0;padding: 0;} .main{ width: 800px; height: 700px; background-color: #999999; position: relative; } .main .main1{ width: 300px; height: 300px; background-color: red; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; } </style> </head> <body> <div class='main'> <div class='main1'></div> </div> </body> </html>
第二種方法:
1.將父級變成單元格,display:table-cell; 設定內部元素垂直對齊vertical-align:middle;
text-align:center; 居中
2.子元素配合父元素,變成行內塊級元素display:inline-block;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> *{margin: 0;padding: 0;} .main{ width: 500px; height: 400px; background-color: #999999; display: table-cell;/*變成表格單元格*/ vertical-align: middle; text-align: center; } .main .main1{ width: 100px; height: 100px; background-color: red; display: inline-block; } </style> </head> <body> <div class='main'> <div class='main1'></div> </div> </body> </html>
第三種與第一種相似
1.給父級加上相對定位position:relative; 給子元素新增絕對定位position:absolute;
設定top,left,margin-top:-自身高度的一半;margin-left:-自身寬度的一半;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> *{margin: 0;padding: 0;} .main{ width: 500px; height: 400px; background-color: #999999; position: relative; } .main .main1{ width: 100px; height: 100px; background-color: red; position: absolute; top: 50%; margin-top: -150px; left: 50%; margin-left: -150px; } </style> </head> <body> <div class='main'> <div class='main1'></div> </div> </body> </html>
第四種 需要用到彈性盒子。簡單方便
1.給彈性容器(父容器)新增display:flex;
2.給彈性容器的子元素加上 margin:auto;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{margin: 0;padding: 0;}
.main{
width: 500px;
height: 400px;
background-color: #999999;
display: flex;
}
.main .main1{
width: 100px;
height: 100px;
background-color: red;
margin: auto;
}
</style>
</head>
<body>
<div class='main'>
<div class='main1'></div>
</div>
</body>
</html>
效果一樣 簡單便捷。