如何使用 CSS 建立等高列?
在網頁的父級 div 中可以建立等高列。首先,將父容器設定為一個寬度為 100% 的表格。在其內,建立列並設定顯示屬性為表格單元格。我們來看看如何使用 HTML 和 CSS 建立等高列。
建立一個父容器
<div class="container"> <div class="column"> <h2>Column 1</h2> <h2>Column 1</h2> <h2>Column 1</h2> </div> <div class="column"> <h2>Column 2</h2> <h2>Column 2</h2> <h2>Column 2</h2> </div> <div class="column"> <h2>Column 3</h2> <h2>Column 3</h2> <h2>Column 3</h2> </div> </div>
將父容器的樣式設定成表格
使用值 table 的 display 屬性建立一個作為表格的父級 div -
.container { display: table; width: 100%; }
建立列 1
為第 1 列建立一個子級 div -
<div class="column"> <h2>Column 1</h2> <h2>Column 1</h2> <h2>Column 1</h2> </div>
建立列 2
為第 2 列建立一個子級 div -
<div class="column"> <h2>Column 2</h2> <h2>Column 2</h2> <h2>Column 2</h2> </div>
建立列 3
為第 3 列建立一個子級 div -
<div class="column"> <h2>Column 3</h2> <h2>Column 3</h2> <h2>Column 3</h2> </div>
設定每個列的樣式
每個列都以 table-cell 屬性進行顯示 -
.column { display: table-cell; padding: 16px; background-color: greenyellow; }
示例
要使用 CSS 建立等高列,程式碼如下 -
<!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .container { display: table; width: 100%; } .column { display: table-cell; padding: 16px; background-color: greenyellow; } .column:nth-of-type(2n-1) { color: red; background-color: yellow; } </style> </head> <body> <h1>Equal Height Columns Example</h1> <div class="container"> <div class="column"> <h2>Column 1</h2> <h2>Column 1</h2> <h2>Column 1</h2> </div> <div class="column"> <h2>Column 2</h2> <h2>Column 2</h2> <h2>Column 2</h2> </div> <div class="column"> <h2>Column 3</h2> <h2>Column 3</h2> <h2>Column 3</h2> </div> </div> </body> </html>
廣告