Open In App

How to make the background of a div clickable in HTML ?

Last Updated : 17 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To make the background of a <div> clickable in HTML, you can use various approaches such as wrapping the <div> in an anchor tag or using JavaScript to handle the click event. Below, we will explore these methods in detail, including syntax examples and how they work.

Using an anchor tag

Wrapping the entire <div> element inside an anchor tag is the simplest way to make the entire background of the <div> clickable. This method automatically turns the entire content area of the <div> into a clickable link, making it easy to redirect users to another page or resource.

Syntax:

<a href="yourLink">
    <div>
        <!-- Your content goes here -->
    </div>
</a>

Example: In this example, we will use the anchor tag to make the background clickable.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Clickable Background</title>
    <style type="text/css">
        .box {
            width: 200px;
            height: 200px;
            background-color: #666764;
            cursor: pointer;
        }

        .box:hover {
            background-color: #000000;
        }
    </style>
</head>

<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <a href=
"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-17.png">
        <div class="box">
            Click me!
        </div>
    </a>
</body>

</html>

Output:

mr

Using JavaScript

Another approach is to use JavaScript to capture the click event on the <div> element. This method allows for more dynamic interactions and can be useful if you want to perform other actions before navigating to the link, such as logging events or confirming with the user.

Syntax:

<div onclick="location.href='yourLink';">
    <!-- Your content goes here -->
</div>

Example: In this example, we will use the above approach.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Clickable Background</title>
    <style type="text/css">
        .box {
            width: 300px;
            height: 300px;
            background-image: url(
'https://media.geeksforgeeks.org/wp-content/uploads/20210720234436/gfglogo2-300x300.jpg');
            cursor: pointer;
        }

        .box:hover {
            opacity: 0.7;
        }
    </style>
</head>

<body>
    <div class="box" onclick="window.location.href=
'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-17.png'">
        Click me!
    </div>
</body>

</html>

Output:

mr

Next Article

Similar Reads