盒子居中4種方式(優選flex)


 1    <title>第一種實現方式:定位 + 偏移(需要知道子元素的寬高)</title>
 2     <style>
 3         .father {
 4             width: 300px;
 5             height: 300px;
 6             background-color: deepskyblue;
 7             margin: 100px auto;
 8             position: relative;
 9         }
10         .son {
11             width: 100px;
12             height: 100px;
13             background-color: pink;
14             /*實現水平垂直居中*/
15             position: absolute;
16             top: 50%;
17             left: 50%;
18             margin-top: -50px;
19             margin-left: -50px;
20         }
21     </style>
22 </head>
23 
24 <body>
25     <div class="father">
26         <div class="son"></div>
27     </div>
28 </body>
 1  <title>第二種實現方式:定位 + transform(不需要知道子元素的寬高)</title>
 2     <style>
 3         .father {
 4             width: 300px;
 5             height: 300px;
 6             background-color: deepskyblue;
 7             margin: 100px auto;
 8             position: relative;
 9         }
10         
11         .son {
12             width: 100px;
13             height: 100px;
14             background-color: pink;
15             /*實現水平垂直居中*/
16             position: absolute;
17             top: 50%;
18             left: 50%;
19             transform: translate(-50%, -50%);
20         }
21     </style>
22 </head>
23 
24 <body>
25     <div class="father">
26         <div class="son"></div>
27     </div>
28 
29 </body>
 1     <title>第三種實現方式:讓父盒子為flex容器Document</title>
 2     <style>
 3         .father {
 4             width: 300px;
 5             height: 300px;
 6             background-color: deepskyblue;
 7             display: flex;
 8             justify-content: center;
 9             align-items: center;
10         }
11         
12         .son {
13             width: 100px;
14             height: 100px;
15             background-color: pink;
16         }
17     </style>
18 </head>
19 
20 <body>
21     <div class="father">
22         <div class="son"></div>
23     </div>
24 </body>

 

 1  <title>第四種實現方式:margin:auto;實現絕對定位元素的水平方向居中</title>
 2     <style>
 3         .father {
 4             width: 300px;
 5             height: 300px;
 6             background-color: deepskyblue;
 7             position: relative;
 8         }
 9         
10         .son {
11             width: 100px;
12             height: 100px;
13             background-color: pink;
14             /*實現水平垂直居中*/
15             position: absolute;
16             top: 0;
17             left: 0;
18             bottom: 0;
19             right: 0;
20             margin: auto;
21         }
22     </style>
23 </head>
24 
25 <body>
26     <div class="father">
27         <div class="son"></div>
28     </div>
29 </body>
30 
31 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM