Chúng ta có thể định nghĩa style cho bảng (table) bằng CSS. Các thuộc tính sau thường được dùng để style <table> và các phần tử con của nó:
5 Thuộc tính chính
| Thuộc tính | Mô tả |
|---|---|
| border | Định nghĩa border-width, border-style, border-color |
| border-collapse | Chỉ định table có border chung (collapse) hay riêng (separate) |
| caption-side | Định vị dọc cho caption box (top/bottom) |
| empty-cells | Hiển thị/ẩn ô trống (show/hide) |
| table-layout | Thuật toán bố cục: auto (mặc định) hoặc fixed |
Ví dụ 1: Border, caption, box-shadow
<!DOCTYPE html>
<html>
<head>
<style>
table, table * {
border: thin solid;
padding: 5px;
font-style: italic;
}
caption { caption-side: bottom; }
td { box-shadow: inset 0 0 6px green; }
</style>
</head>
<body>
<table>
<caption>Demo caption</caption>
<tr><td>demo</td></tr>
<tr><td>demo</td><td></td></tr>
<tr><td>demo</td><td>demo</td><td></td></tr>
</table>
</body>
</html>
Ví dụ 2: border-collapse: collapse vs separate
<!DOCTYPE html>
<html>
<head>
<style>
div { display: flex; float: left; margin-right: 20px; }
table { border: 3px solid black; }
td { border: 3px solid lightgreen; }
th { border: 3px solid lightblue; }
#t2 { border-collapse: collapse; }
</style>
</head>
<body>
<h2>Team Rankings</h2>
<div>
<table id="t1"> <!-- separate (mặc định) -->
<tr><th>Team (Test)</th><th>Rank</th></tr>
<tr><td>India</td><td>1</td></tr>
<tr><td>Australia</td><td>2</td></tr>
</table>
</div>
<div>
<table id="t2"> <!-- collapse -->
<tr><th>Team (ODI)</th><th>Rank</th></tr>
<tr><td>India</td><td>1</td></tr>
<tr><td>England</td><td>2</td></tr>
</table>
</div>
</body>
</html>
Chi tiết các thuộc tính
border-collapse
separate(mặc định): Mỗi cell có border riêng, có khoảng cách (border-spacing)collapse: Border chung, gộp thành một đường,border-spacingbị bỏ qua
table-layout
auto(mặc định): Browser tính toán width dựa trên nội dung — chậm hơn, linh hoạtfixed: Width dựa trên<col>hoặc row đầu tiên — nhanh hơn, width ổn định
table { table-layout: fixed; width: 100%; }
col:first-child { width: 30%; }
col:last-child { width: 70%; }
empty-cells
show(mặc định): Hiển thị border/background ô trốnghide: Ẩn border/background ô trống- Chỉ hoạt động khi
border-collapse: separate
caption-side
top(mặc định),bottom- Có thể dùng
caption-side: bottomcho chú thích bảng
Modern Table Styling Best Practices
.table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
}
.table th,
.table td {
padding: 0.75rem 1rem;
border: 1px solid #dee2e6;
text-align: left;
}
.table thead th {
background-color: #f8f9fa;
font-weight: 600;
}
.table tbody tr:nth-child(even) {
background-color: #f8f9fa;
}
.table tbody tr:hover {
background-color: #e9ecef;
}
.table-responsive {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}