Appearance
How to Make a Div a Clickable Link
<div> elements are important in CSS-based web design as they give structure to HTML. Sometimes you may need to make the whole <div> element clickable as a link. To do this, you can find some methods in our snippet and choose the appropriate method for you.
Follow the given steps for the first solution. It's about making an anchor tag inside a div, and styling the anchor so it covers all the area inside the div
DANGER
The first solution uses CSS absolute positioning, which is a bad practice most of the time. You can scroll down to see the other solution.
Create HTML
- Create a
<div>with a class name "container". - Use the
<a>element to add the needed link.
How to Make a Div a Clickable Link
html
<body>
<div class="container">
W3Docs
<a href="https://www.w3docs.com/"></a>
</div>
</body>Create CSS
- Set the position to "absolute" for the inner
<a>tag. - Use the z-index property to place the link above all the other elements in the div.
- Apply
display: blockto the anchor to make it cover the container area.
How to Make a Div a Clickable Link
css
.container {
font-size: 5em;
background-color: #a8a8a8;
color: white;
width: 8em;
height: 2em;
line-height: 2;
text-align: center;
font-family: Helvetica, Arial, sans-serif;
font-weight: bold;
cursor: pointer;
position: relative;
}
.container a {
display: block;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 1;
}Let’s see the full code.
Example of making a div a clickable link:
Example of making a div a clickable link:
html
<!DOCTYPE HTML>
<html>
<head>
<style>
.container {
font-size: 5em;
background-color: #a8a8a8;
color: white;
width: 8em;
height: 2em;
line-height: 2;
text-align: center;
font-family: Helvetica, Arial, sans-serif;
font-weight: bold;
cursor: pointer;
position: relative;
}
.container a {
display: block;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 1;
}
</style>
</head>
<body>
<div class="container">
W3Docs
<a href="https://www.w3docs.com/"></a>
</div>
</body>
</html>Result
You can also use the <div> nested inside a hyperlink.
Second solution: making a div a clickable link by nesting it in the <a> tag:
Example of making a div a clickable link by nesting it in the <a> tag:
html
<!DOCTYPE HTML>
<html>
<head>
<style>
a {
display: block;
background: orange;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<a href="https://www.w3docs.com/learn-html/html-introduction.html">
<div>
This is a clickable div.
</div>
</a>
</body>
</html>As the div is nested inside the anchor tag, the anchor tag covers all the div's area, and thus the div becomes a clickable link. Note: HTML5 allows block-level elements like <div> inside <a> tags. For better accessibility, ensure the link text is descriptive and visible to screen readers.