Explain Codes LogoExplain Codes Logo

Giving a border to an HTML table row, ``

html
responsive-design
css
best-practices
Anton ShumikhinbyAnton Shumikhin·Oct 3, 2024
TLDR

To give a border to an HTML table row, you need to set the border on the <td> or <th> elements inside the row. Applying border-collapse: collapse; on the <table> ensures that borders are rendered seamlessly.

<table style="border-collapse: collapse;"> <tr> <td style="border: 1px solid black;">Cell 1</td> <td style="border: 1px solid black;">Cell 2</td> <td style="border: 1px solid black;">Cell 3</td> </tr> </table>

Deeper Dive: Advanced Styling

Specific row styles

To style particular rows, use the clever trick of the tr:nth-child() pseudo-class. This allows flexibility, permitting variations in styles across different rows. Yep, your code just got smarter!

table { border-collapse: collapse; } tr:nth-child(even) { background-color: #f2f2f2; } tr:nth-child(odd) { background-color: white; }

Styling with classes and IDs

Maximize efficiency by using classes or IDs for applying custom borders to exclusive rows. You’ll thank yourself later for the cleaner, less redundant code. This is like a VIP pass, but for your code.

<tr class="bordered"> <td>...</td> <td>...</td> </tr>
.bordered td { border: 2px solid blue; }

Outline: Border's alternate universe

Meet the outline property - the border's long-lost sibling. It gives an uncanny border-like vibe without impacting the layout. To put it simply: outline is to border what Clark Kent is to Superman!

tr.highlight { outline: 2px solid red; }

Rounded corners and faux borders

Border-radius on your <td> elements can yield rounded corners. Yes, it's like table cells taking selfies with the fish-eye filter. Combine this with box-shadow to fake out a border for the whole row.

tr.rounded-box { box-shadow: 0 0 0 3px #333; border-radius: 10px; }

Solving border disputes

When <td> elements with different borders end up side by side, it looks weird. So set a uniform border for all nested <td> or <th> within a classed <tr>. It’s the CSS equivalent of calling a truce.

.tr-border td, .tr-border th { border: 1px solid #000; }

Consistent look across browsers

To ensure uniform borders across different browsers, explicitly use border-collapse: collapse;. Remember, not all browsers play by the same rules!

table { border-collapse: collapse; }

Designer borders

Use :first-child and :last-child pseudo-classes to customise the edges of <tr>. It's like giving your table a hipster haircut.

.tr-edge-style > :first-child { border-left: 2px solid green; } .tr-edge-style > :last-child { border-right: 2px solid green; }