Skip to content Skip to sidebar Skip to footer

How Can I Make An Entire Div A Link, But Also Have Other Links Inside?

I have a div. I want it to link somewhere when you click on it, but I also want to put other links inside it, so when you click on the other links you're redirected to one place, b

Solution 1:

You can use the javascript onclick event on the parent element of the link(s):

.exterior {
  display: block;
  width:100px;
  height:100px;
  border: 1px black solid;
}
<divonclick="document.location.href='https://example.com';return true;"class="exterior"><ahref="https://stackoverflow.com">interior</a></div>

I don't recommend to use <a> in <a> element. Using <a> in <a> isn't valid. You can check the following document on the W3C validator:

<!DOCTYPE html><html><head><title>test link in link</title></head><body><ahref="#"class="test1"><ahref="#"class="test2">test</a></a></body></html>

You can also use two different <a> elements (without using javascript - only CSS solution):

div {
  position:relative;
  border:1px solid red;
  height:200px;
  width:200px;
}
diva.ext {
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  z-index:0;
}
diva.int {
  position:relative;
  z-index:999;
}
<div><aclass="ext"href="https://example.com"></a><aclass="int"href="https://stackoverflow.com">test</a></div>

Solution 2:

A simple, practical, non-javascript solution:

Break up your main link into smaller chunks - something like:

<div><ahref="#"class="exterior">First part of exterior link</a><ahref="#">interior</a><ahref="#"class="exterior">Second part of exterior link etc</a></div>

Solution 3:

You can use absolute positioning

.exterior {
  display: block;
  width:100px;
  height:100px;
  border: 1px black solid;
  position: relative;
}
.interior {
  position: absolute;
  top: 20px;
  left: 20px;
}
<ahref="bla"class="exterior"><aclass="interior"href="blabla">Interior</a></a>

Solution 4:

$(".exterior a").click(function(e){
    alert('a clicked but div not triggered');
    e.stopPropagation();
});

$(".exterior").click(function(e){
    alert("div clicked but not a");
})

<div href = "#"class="exterior">
  <ahref="https://stackoverflow.com/questions/tagged/css">interior</a>
</div>

.exterior{
width: 500px;
height: 100px;
background-color: red;
}

I used stop propagation on a element to prevent it from triggering the click on the div. And i used div as wrapper so you would have to put a windows.location if you want to redirect to an url inside the click function.

I'm not sure how you can achieve this with simply html and css. So i would suggest using jquery.

Solution 5:

.exterior {
  display: block;
  width:100px;
  height:100px;
  border: 1px black solid;
}
<ahref="http://bing.com"class="exterior"><object><ahref="http://example.com">Interior</a></object></a>

demo

Post a Comment for "How Can I Make An Entire Div A Link, But Also Have Other Links Inside?"