目前,在大多數開發環境中,已經基本不用table元素來做網頁布局了,取而代之的是div+css,那么為什么不用table系表格元素呢?
1、用DIV+CSS編寫出來的文件k數比用table寫出來的要小,不信你在頁面中放1000個table和1000個div比比看哪個文件大
2、table必須在頁面完全加載后才顯示,沒有加載完畢前,table為一片空白,也就是說,需要頁面完畢才顯示,而div是逐行顯示,不需要頁面完全加載完畢,就可以一邊加載一邊顯示
3、非表格內容用table來裝,不符合標簽語義化要求,不利於SEO
4、table的嵌套性太多,用DIV代碼會比較簡潔
但是有的項目中又需要類似表格的布局怎么辦呢?可以用display:table來解決
display:table系列幾乎是和table系的元素相對應的,請看下表:
table | (類似 <table>)此元素會作為塊級表格來顯示,表格前后帶有換行符。 |
inline-table | (類似 <table>)此元素會作為內聯表格來顯示,表格前后沒有換行符。 |
table-row-group | (類似 <tbody>)此元素會作為一個或多個行的分組來顯示。 |
table-header-group | (類似 <thead>)此元素會作為一個或多個行的分組來顯示。 |
table-footer-group | (類似 <tfoot>)此元素會作為一個或多個行的分組來顯示。 |
table-row | (類似 <tr>)此元素會作為一個表格行顯示。 |
table-column-group | (類似 <colgroup>)此元素會作為一個或多個列的分組來顯示。 |
table-column | (類似 <col>)此元素會作為一個單元格列顯示。 |
table-cell | (類似 <td> 和 <th>)此元素會作為一個表格單元格顯示。 |
table-caption | (類似 <caption>)此元素會作為一個表格標題顯示。 |
目前display:table的應用場景也是比較廣泛的,Google地圖在搜索路線時,左側的路線詳情就是用的display:table來實現的。
1.div模擬表格:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>模擬表格</title> </head> <body> <style type="text/css" rel="stylesheet"> .table { display: table; border: 1px solid #cccccc; margin: 5px; /*display: table時padding會失效*/ } .row { display: table-row; border: 1px solid #cccccc; /*display: table-row時margin、padding同時失效*/ } .cell { display: table-cell; border: 1px solid #cccccc; padding: 5px; /*display: table-cell時margin會失效*/ } </style> <div class="table"> <div class="row"> <div class="cell">張三</div> <div class="cell">李四</div> <div class="cell">王五</div> </div> <div class="row"> <div class="cell">張三</div> <div class="cell">李四</div> <div class="cell">王五</div> </div> </div> </body> </html>
2.讓塊級標簽實現行內效果,即浮動至同一橫軸,並實現等高效果
table表格中的單元格最大的特點之一就是同一行列表元素都等高。所以,很多時候,我們需要等高布局的時候,就可以借助display:table-cell
屬性。說到table-cell
的布局,不得不說一下“匿名表格元素創建規則”:
CSS2.1表格模型中的元素,可能不會全部包含在除HTML之外的文檔語言中。這時,那些“丟失”的元素會被模擬出來,從而使得表格模型能夠正常工作。所有的表格元素將會自動在自身周圍生成所需的匿名table對象,使其符合table/inline-table、table-row、table- cell的三層嵌套關系。
舉個例子吧,如果我們為元素使用“display:table-cell;”屬性,而不將其父容器設置為“display:table-row;”屬性,瀏覽器會默認創建出一個表格行,就好像文檔中真的存在一個被聲明的表格行一樣。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>display:table實現浮動效果</title> </head> <body> <style type="text/css" rel="stylesheet"> .table { display: table; margin: 5px; width: 1000px; } .row { display: table-row; } .cell { display: table-cell; padding: 10px; background-color: red; } </style> <div class="table"> <div class="row"> <div class="cell">內容內容內容內容內容內內容內</div> <div class="cell">內容內容內容內容內容內容內容內容內容</div> <div class="cell">內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容</div> </div> </div> </body> </html>
上例中div.row可以不要,效果一樣
3.結合vetical-align實現塊級元素垂直居中