Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling table borders with CSS

Tags:

html

css

I'm trying to do something very simple: create a table with single line borders.

There are many articles saying how to do that, and almost all of them include something like

table {
   border-collapse: collapse;
  }
td, th {
   border: 1px solid orange;
  }

Which works great.

But they all apply the styling universally to the td and th tags themselves, and therefore apply to all tables.

So I tried this

.bordered {
    border-collapse: collapse;
    border: 1px solid orange;
    text-align: center;
    color: blue;
 }
<table class=bordered>
    <tr> <td> ABC </td> <td> DEF </td> </tr> 
    <tr> <td> HIJ </td> <td> JLK </td> </tr>
</table>

I get a table with orange outer border, blue letters, and no internal borders.
I also tried

table.bordered, tr.bordered, td.bordered { 

to no avail. Also putting "class=" on the tr tags didn't help.

I have learned that border properties are not inherited.
The DOM Inspector confirms that: just the color and centering are inherited by the td elements from the .bordered class.

My question is this:

How do I get borders on the cells without adding "class=" to every single td tag?

(A use case would if there are two tables on the page, and I want the borders styled differently for them).

like image 576
T G Avatar asked May 03 '26 20:05

T G


1 Answers

Just take the css that works for all tables, and add table.bordered before all of them:

table.bordered {
   border-collapse: collapse;
}
table.bordered td,  table.bordered th {
   border: 1px solid orange;
}
<table class="bordered">
    <tr> <td> ABC </td> <td> DEF </td> </tr> 
    <tr> <td> HIJ </td> <td> JLK </td> </tr>
</table>

<table>
    <tr> <td> ABC </td> <td> DEF </td> </tr> 
    <tr> <td> HIJ </td> <td> JLK </td> </tr>
</table>
like image 54
dave Avatar answered May 05 '26 14:05

dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!