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

To make the background of a div clickable in HTML, add an onclick attribute to the div element with JavaScript code or wrap the div’s content in an anchor tag. Alternatively, utilize CSS pseudo-elements like ::before or ::after and apply pointer-events: none to the parent div.

Table of Content

  • Using an anchor tag
  • Using JavaScript

Using an anchor tag

The first approach is to wrap the entire <div> element inside an anchor tag (<a>). This way, clicking anywhere inside the <div> will trigger the link.

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">w3wiki</h1>
    <a href=
"https://media.w3wiki.net/wp-content/uploads/w3wiki-17.png">
        <div class="box">
            Click me!
        </div>
    </a>
</body>

</html>

Output:

background of a div clickable in HTML Example Output

Using JavaScript

The second approach is to use JavaScript to capture the click event on the <div> element and redirect the user to the desired link.

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.w3wiki.net/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.w3wiki.net/wp-content/uploads/w3wiki-17.png'">
        Click me!
    </div>
</body>

</html>

Output:

background of a div clickable in HTML Example Output