Open In App

How to Set Background Image in HTML Table ?

Setting a background image in an HTML table can enhance the visual appeal of your webpage. In this article, we will discuss two methods to set a background image in an HTML table i.e. using inline CSS and external CSS.

Set Background Image in HTML Table using Inline CSS

In this approach, we directly apply the CSS style to the <table> tag using the style attribute.






<!DOCTYPE html>
<html>
  
<head>
    <title>Background Image in Table</title>
  
    <style>
        table {
            margin: auto;
        }
  
        table, tr td {
            border: 1px solid black;
        }
    </style>
</head>
  
<body>
    <table style="background-image: url('https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png'); width: 400px; height: 200px;">
        <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
        </tr>
        <tr>
            <td>Cell 3</td>
            <td>Cell 4</td>
        </tr>
        <tr>
            <td>Cell 3</td>
            <td>Cell 4</td>
        </tr>
        <tr>
            <td>Cell 3</td>
            <td>Cell 4</td>
        </tr>
    </table>
</body>
  
</html>

Output



Explanation

Set Background Image in HTML Table using External CSS

In this method, we use an external CSS file to style the table. This approach is more maintainable and scalable.




<!DOCTYPE html>
<html>
  
<head>
    <title>Background Image in Table</title>
    <link rel="stylesheet" href="style.css">
</head>
  
<body>
    <table class="background-table">
        <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
        </tr>
        <tr>
            <td>Cell 3</td>
            <td>Cell 4</td>
        </tr>
        <tr>
            <td>Cell 3</td>
            <td>Cell 4</td>
        </tr>
        <tr>
            <td>Cell 3</td>
            <td>Cell 4</td>
        </tr>
    </table>
</body>
  
</html>




/* Filename: style.css */
  
table {
    margin: auto;
}
  
table, tr td {
    border: 1px solid black;
}
  
.background-table {
    width: 400px;
    height: 200px;
}

Output:

Explanation


Article Tags :