Open In App

How to Change the Background Color of Table using CSS?

Changing the background color of a table using CSS can help improve the visual appearance of a website or web application. we will learn how to change the background color of the table using CSS with different approaches.

These are the following approaches:

Using Inline CSS

In this approach, we are using Inline CSS which involves applying styles directly to HTML elements using the style attribute. To change the background color of a table using inline CSS, we can use the background-color property.

Syntax:

<table style="background-color: colorName;">
<!-- table content -->
</table>

Example: The below example uses the Inline CSS to Change the Background Color of Table.

<!DOCTYPE html>
<html>
<head>
  <title>Inline CSS Example</title>
</head>
<body>
    <table style="background-color: yellow;" border="1">
        <thead>
            <tr>
              <th>First Name</th>
              <th>Last Name</th>
              <th>Age</th>
            </tr>
          </thead>
          <tbody>
            <tr>
                <td>Virat</td>
                <td>Kohli</td>
                <td>39</td>
              </tr>
              <tr>
                <td>MS</td>
                <td>Dhoni</td>
                <td>47</td>
              </tr>
              <tr>
                <td>Rohit</td>
                <td>Sharma</td>
                <td>35</td>
              </tr>
          </tbody>
        </table>
</body>
</html>

Output:

Screenshot-(74)

Using Internal CSS

In this approach we are using internal CSS to change the background color of a table, Here we define the CSS styles within a <style> tag and we set the background-color property of the table to the desired color.

Example: The below example uses the Internal CSS to Change the Background Color of Table.

<!DOCTYPE html>
<html>
<head>
  <title>Internal CSS Example</title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
      background-color: lightblue;
    }
    th, td {
      border: 1px solid black;
      padding: 8px;
      text-align: center;
    }
  </style>
</head>
<body>
  <table>
    <thead>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Age</th>
        </tr>
      </thead>
      <tbody>
        <tr>
            <td>Virat</td>
            <td>Kohli</td>
            <td>39</td>
          </tr>
          <tr>
            <td>MS</td>
            <td>Dhoni</td>
            <td>47</td>
          </tr>
          <tr>
            <td>Rohit</td>
            <td>Sharma</td>
            <td>35</td>
          </tr>
      </tbody>
    </table>
</body>
</html>

Output:


ms

Article Tags :