Trusha_Patel
Trusha_Patel

Reputation: 71

CSS styling override for table and table cells

I have used the element to define the table element with a background colour of light-grey. Also, I tried to add the id attribute to specify a few tables whose background-colour should be different from the "generalized" one.

Here is the code:

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td { 
  background-color:#f2f2f2;
  border: 1px solid black;
  border-collapse: collapse;
}
th, td {
  padding: 15px;
  text-align: left;
}
#t01 {
  width: 100%;    
  background-color: blue;
}
</style>
</head>
<body>

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
<tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>
<br>

<table id="t01">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

</body>
</html>

However, I am unable to override the table style defined earlier. I can't get the id's properties to be executed. Both the table outputs with the same background-colour; light-grey. How to enable the override in such cases?

Upvotes: 0

Views: 63

Answers (1)

Minal Chauhan
Minal Chauhan

Reputation: 6148

You also need to add css for th and td for second table like this: #t01 th, #t01 td {background-color: blue;}

table, th, td { 
  background-color:#f2f2f2;
  border: 1px solid black;
  border-collapse: collapse;
}
th, td {
  padding: 15px;
  text-align: left;
}
#t01 {
  width: 100%;    
  background-color: blue;
}
#t01 th, #t01 td {
  background-color: blue;
  color: #fff;
}
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
<tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>
<br>

<table id="t01">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

Upvotes: 1

Related Questions