Syling Tables Flashcards
How do you make a table scroll horizontally on small screens instead of shrinking its content?
CSS
.table-container { overflow-x: auto; max-width: 100%; } table { width: 100%; border-collapse: collapse; }
HTML
<div class="table-container"> <table> <tr> <th>Name</th> <th>Age</th> </tr> <tr> <td>John</td> <td>25</td> </tr> </table> </div>
This wraps the table in a scrollable div so it doesn’t break on small screens.
What is the difference between border-collapse: separate;
and border-collapse: collapse;
when styling table borders?
border-collapse: collapse;
merges adjacent table borders into one.
border-collapse: separate;
keeps individual cell borders separate.
table { border-collapse: collapse; /* Borders merge */ } th, td { border: 1px solid black; }
This removes double borders between cells.
How can you add alternating row colors (striped effect) to a table?
tr:nth-child(even) { background-color: #f2f2f2; /* Light gray for even rows */ }
This improves readability by highlighting every other row.
How can you make the <thead>
stay fixed at the top while scrolling down a long table?
thead { position: sticky; top: 0; background: white; z-index: 10; }
This keeps the table header visible while scrolling.
How can you center-align text in table cells but right-align numbers?
CSS
td { text-align: center; /* Center text */ } td.numeric { text-align: right; /* Right-align numbers */ }
HTML
<tr> <td>Product</td> <td class="numeric">100</td> </tr>
This ensures better data readability, especially for financial tables.
How do you change a row’s background color when the user hovers over it?
tr:hover { background-color: lightblue; }
This improves user experience by giving visual feedback when hovering.
Why should you use padding inside <td>
elements instead of margin?
Tables do not allow margins inside cells, so you should use padding:
td { padding: 10px; }
This creates space inside the cell without breaking table structure.
How can you make a table take full width of the page while ensuring one column does not exceed 200px?
table { width: 100%; } td:first-child { max-width: 200px; word-wrap: break-word; }
This ensures the first column doesn’t stretch too wide while keeping the table responsive.
Why would you use border-spacing: 0;
in a table?
table { border-spacing: 0; }
By default, tables add spacing between cells.
How can you create a table with no visible borders but still keep cell spacing?
table { border: none; border-collapse: separate; border-spacing: 10px; }
This removes borders while keeping space between cells for a clean look.