TransWikia.com

CSS works fine for table 'tr' and 'td' but fails if I include 'th'

Stack Overflow Asked by user3750702 on December 3, 2021

I have a few tables on my site, mostly without borders. But I want to draw borders on some. I am using class for the latter in my CSS:

table {
  padding: 2px;
  border-collapse: collapse;
  table-layout: auto;
  text-align: center;
  display: block;
}

table.tableAllBorder tr td{
  border-right: solid 1px; 
  border-left: solid 1px;
  border-top: solid 1px; 
  border-bottom: solid 1px;
}

This works fine. But CSS fails if I include ‘th’ in the definition, as follows:

table.tableAllBorder tr td th{
  border-right: solid 1px; 
  border-left: solid 1px;
  border-top: solid 1px; 
  border-bottom: solid 1px;
}

Ideally I would like to just include border="1" when I define my table. In that case I see a double border, far outside my table (please see attached screenshot). Please advice.

<table border="1">
</table>

enter image description here

Edit:
My css:

html, body {
  background-color: rgb(var(--color5));
  font-family: sans-serif;
  -webkit-transition: height 0.3s;
  -moz-transition: height 0.3s;
  transition: height 0.3s;
}

.div1
{
  margin-left: 40px;
  overflow-x:auto;
  width:auto;
}

table {
  padding: 2px;
  border-collapse: collapse;
  table-layout: auto;
  text-align: center;
  display: block;
}

table tr:nth-child(odd) {
  background-color: rgb(var(--color4));
}

table tr:nth-child(even) {
  background-color: rgb(var(--color5));
}

table.tableAllBorder tr td th{
  border-right: solid 1px rgb(var(--color1)); 
  border-left: solid 1px rgb(var(--color1));
  border-top: solid 1px rgb(var(--color1)); 
  border-bottom: solid 1px rgb(var(--color1));
}

and my html code:

<div class="div1">
<table border="1"  class="center">
<tr>
 <th> ColA </th>
 <th> ColB </th>
 <th> ColC </th>
 <th> ColD  </th>
 <th> ColE </th>
 <th> ColF </th>
 <th> ColG </th>
 <th> ColH </th>
 </tr>
</table>
</div>

One Answer

Don't use border=1. Such markup is outdated and isn't semantic HTML. Use a class with border: 1px solid black.

If you include th in your CSS, your are selecting only the th element. You need to make a separate class.

table.tableAllBorder tr td {
   /* your original stuff */
}

table.tableAllBorder tr th { /* new selector */ }

We don't see your markup, but that's assuming you have the following legal HTML:

<table class="tableAllBorder">
  <tr>
    <th>Header</th>
    ...
  </tr>
  <tr>
    <td></td>
    ...
  </tr>
  <tr>
    <td></td>
    ...
  </tr>
</table>

Answered by Denis G. Labrecque on December 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP