# CSS 33. table styling / 表格樣式設計 ### border-collapse: - 假設我有個表格長這樣: ``` <table> <tr> <th>標題一</th> <th>標題二</th> <th>標題三</th> </tr> <tr> <td>內容一</td> <td>內容二</td> <td>內容三</td> </tr> <tr> <td>內容1</td> <td>內容2</td> <td>內容3</td> </tr> </table> ``` ![](https://i.imgur.com/TgoxEi5.png) ### 這時候你會需要一個線條來優化它的視覺效果: - 記得,要在 table 表格增加「格線」時, `table` , `th` , `td` 都要加入 ``` // css example: table , th , td { border: 1px solid #000; } ``` - 接下來會看到這樣的節果: ![](https://i.imgur.com/qdjunfN.png) - 你可能會想說: Fuck!`這不是老子要的效果對吧?`,主要原因是: 我們先將 `th` , `td` 給拿掉試試看: ``` // css example: table{ border: 1px solid #000; } ``` ![](https://i.imgur.com/sgapPOw.png) - 此時即可發現,你只留下最外框了,那其實就是 table 標籤的一個範圍 那麼理所當然,`th`,`td`也會自成一個方框來呈現。 ### 如何解決? 加入邊界崩塌: - border-collapse: ``` // th,td 加回去 table,th,td { border-collapse: collapse; border: 1px solid #000; } ``` ![](https://i.imgur.com/Fa0VAC3.png) - 原本兩個框框包住的醜醜線條終於聽話了:D --- ### table 設定長寬: - 僅需要透過 `table` 標籤,則可以設定整體表格長寬 會跟著拉動 `th`,`td`。 ``` table { width: 300px; height: 150px; } ``` --- ### 表格內可設定 padding,使文字與框線不會太擁擠。 ``` th,td { /* or px */ padding: 0.5rem 1rem; } ``` ![](https://i.imgur.com/453p2G3.png) --- ### 針對 table 設計 background-color,`th` 為例: ``` th { background-color: #5cca8d; } ``` ![](https://i.imgur.com/BCTQQpE.png) --- ### 利用 hover,讓表格更具有互動感: - 設定在 `td`: ``` td:hover { background-color: #3de165; transition: all 1s; } ``` - 實際效果樣式: 參考此 [codepen](https://codepen.io/rrpaqjcq/pen/YzvMdNb) ###### tags: `2022 網頁開發全攻略教程 / CSS篇章 - CSS 進階-1`