Open In App

How to change opacity of every data element on hover in a table using CSS ?

There is a Table made by using HTML in which data elements are set to a low opacity. The task is to change the opacity of a particular element when user hover over data elements.

To make a table look better, we will use gradient colors to set backgrounds of the table data elements. In this approach, we will be using the opacity property of CSS to complete the task.



opacity: The opacity property is used in the image to describe the transparency of the image. The value of opacity lies between 0.0 to 1.0 where the low value represents high transparent and high value represents low transparent.

Approach: 



Example:




<!DOCTYPE html>
<html>
  
<head>
    <title>Table Styling</title>
      
    <style>
        h1 {
            text-align: center;
            margin-top: 5vw;
            color: green;
        }
  
        table {
            margin-left: 25vw;
        }
  
        th {
            text-align: center;
            width: 200px;
            color: white;
            background-image:linear-gradient(
                to bottom, #6B8E23, #556B2F);
            height: 40px;
            padding: 0px 10px;
            border-bottom: 3px solid #9ACD32;
            border-radius: 5px 5px 0px 0px;
        }
  
        td:nth-child(odd):hover {
            opacity: 1;
        }
  
        td:nth-child(even):hover {
            opacity: 1;
        }
  
        td {
            opacity: 0.7;
            border-radius: 2px;
            text-align: center;
            vertical-align: middle;
            height: 40px;
            background: rgb(144, 238, 144, 0.3);
            padding: 0px 10px;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
    <table>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Address</th>
        </tr>
        <tr>
            <td>Name 1</td>
            <td>Age 1</td>
            <td>Address 1</td>
        </tr>
        <tr>
            <td>Name 2</td>
            <td>Age 2</td>
            <td>Address 2</td>
        </tr>
        <tr>
            <td>Name 3</td>
            <td>Age 3</td>
            <td>Address 3</td>
        </tr>
        <tr>
            <td>Name 4</td>
            <td>Age 4</td>
            <td>Address 4</td>
        </tr>
    </table>
</body>
  
</html>

Output:

You can see that when mouse hover over <td> elements, their opacity changes to 1 and they seem more clear and defined.


Article Tags :