CSS實現三列布局


三列布局指的是兩邊兩列定寬,中間的寬度自適應。

常用三種方法:

  • 定位
  • 浮動
  • 彈性盒布局

 

定位方式

最直觀和容易理解的一種方法,左右兩欄選擇絕對定位,固定於頁面的兩側,中間的主體選擇用margin確定位置

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>定位方法創建三列布局</title>
 6     <style>
 7     *{
 8         margin: 0;
 9         padding: 0;
10     }
11     .left{
12         width: 200px;
13         height: 500px;
14         background-color: yellow;
16         position: absolute; /* 絕對定位,使位置固定 */
17         left: 0;
18         top: 0;
19     }
20     .center{
21         height: 600px;
22         background-color: purple;
23         margin: 0 300px 0 200px;   /* 通過外邊距確定寬度 */
24     }
25     .right{
26         width: 300px;
27         height: 500px;
28         background-color: red;
30         position: absolute; /* 絕對定位,使位置固定 */
31         right: 0;
32         top: 0;
33     }
34 
35     </style>
36 </head>
37 <body>
38     <div class="left">Left</div>
39     <div class="center">Center</div>
40     <div class="right">Right</div>
41 </body>
42 </html>

結果

 

浮動方法

讓左右兩邊部分浮動,脫離文檔流后對中間部分使用margin來自適應

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>浮動法創建三列布局</title>
 6     <style>
 7         *{
 8             margin: 0;
 9             padding: 0;
10         }
11         .left{
12         width: 200px;
13         height: 500px;
14         background-color: yellow;
15         float: left;
16     }
17     .center{
18         height: 600px;
19         background-color: purple;
20         margin: 0 300px 0 200px;
21         min-width: 100px;  /* 最小寬度,防止瀏覽器縮小后中間部分被隱藏 */
22     }
23     .right{
24         width: 300px;
25         height: 500px;
26         background-color: red;
27         float: right;
28     }
29     </style>
30 </head>
31 <body>
32     <div class="left">Left</div>
33     <div class="right">Right</div>
34     <div class="center">Center</div>  <!-- 左右部分脫離文檔流,中間部分平鋪 -->
35 </body>
36 </html>

 

彈性盒布局

使用容器包裹三欄,並將容器的display設置為flex,左右兩部分寬度設置為固定,中間flex設置為1,左右兩邊的值固定,所以中間的自適應

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>彈性盒子創建三列布局</title>
 6     <style>
 7         *{
 8             margin: 0;
 9             padding: 0;
10         }
11         .container{
12             display: flex;
13         }
14         .left{
15         width: 200px;
16         height: 500px;
17         background-color: yellow;
18     }
19     .center{
20         height: 600px;
21         flex: 1;
22         background-color: purple;
23     }
24     .right{
25         width: 300px;
26         height: 500px;
27         background-color: red;
28     }
29     </style>
30 </head>
31 <body>
32     <div class="container">
33         <div class="left">Left</div>
34         <div class="center">Center</div>  
35         <div class="right">Right</div>
36     </div>
37 </body>
38 </html>

 


免責聲明!

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



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