如何使用 CSS 建立一個 2 列布局網格?


若要建立網頁上的 2 列布局網格,我們將建立並定位兩個 div,一個在左側,另一個在右側。

建立第一個 div

首先,我們將建立一個 div,從左側 div 開始 −

<div class="left">
   <h2>Some random text on the left</h2>
</div>

建立第二個 div

建立第 2 個 div,即右側 div −

<div class="right">
   <h2>Some random text on the right</h2>
</div>

將 div 定位到左側和右側

使用 leftright 屬性將兩個 div 定位到左側和右側 −

.left {
   left: 0;
   background-color: rgb(36, 0, 95);
}
.right {
   right: 0;
   background-color: rgb(56, 1, 44);
}

修復 div

使用 position 屬性的 fixed 值將 div 定位到固定位置 −

.left, .right {
	height: 50%;
	width: 50%;
	position: fixed;
	overflow-x: hidden;
	padding-top: 20px;
}

示例

若要使用 CSS 建立 2 列布局網格,程式碼如下 −

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1" />
   <style>
      body {
         font-family: Arial;
         color: white;
      }
      .left, .right {
         height: 50%;
         width: 50%;
         position: fixed;
         overflow-x: hidden;
         padding-top: 20px;
      }
      .left {
         left: 0;
         background-color: rgb(36, 0, 95);
      }
      .right {
         right: 0;
         background-color: rgb(56, 1, 44);
      }
   </style>
</head>
<body>
   <h1 style="color: black;">Two column layout grid example</h1>
   <div class="left">
      <h2>Some random text on the left</h2>
   </div>
   <div class="right">
      <h2>Some random text on the right</h2>
   </div>
</body>
</html>

更新於: 2023 年 11 月 17 日

超過 2K 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.