的东西,但它是有效的 XHTML 1.1。" />
的东西,但它是有效的 XHTML 1.1。">
的东西,但它是有效的 XHTML 1.1。" />
ChatGPT解决这个技术问题 Extra ChatGPT

Make a div into a link

I have a <div> block with some fancy visual content that I don't want to change. I want to make it a clickable link.

I'm looking for something like <a href="…"><div> … </div></a>, but that is valid XHTML 1.1.

one good reason would be a background image in the div
I have a good working example based on the most voted answer. Check the fiddle here
In HTML5 it is perfectly valid to have a div under an a.

t
thepeer

Came here in the hope of finding a better solution that mine, but I don't like any of the ones on offer here. I think some of you have misunderstood the question. The OP wants to make a div full of content behave like a link. One example of this would be facebook ads - if you look, they're actually proper markup.

For me the no-nos are: javascript (shouldn't be needed just for a link, and very bad SEO/accessibility); invalid HTML.

In essence it's this:

Build your panel using normal CSS techniques and valid HTML.

Somewhere in there put a link that you want to be the default link if the user clicks on the panel (you can have other links too).

Inside that link, put an empty span tag (, not - thanks @Campey)

give the panel position:relative

apply the following CSS to the empty span: { position:absolute; width:100%; height:100%; top:0; left: 0; z-index: 1; /* fixes overlap error in IE7/8, make sure you have an empty gif */ background-image: url('empty.gif'); } It will now cover the panel, and as it's inside an tag, it's a clickable link

give any other links inside the panel position:relative and a suitable z-index (>1) to bring them in front of the default span link


Thanks works well. If things break horribly (like they did for me) in IE8, make sure you have an opening and closing span tag (), instead of an empty span ().
Have you tried this in IE9? I like this method, and I am using it, but I just tested it (including the fiddle from @AlexMA) in IE9, and what I'm seeing is that you can click anywhere in the div EXCEPT on the text. When you hover over the text, the cursor changes to a standard text cursor and it does nothing when you click on the text. As users are prone to click on text elements (and when the text elements fill up most of the div), it makes this solution unusable in IE9. Has anyone else experienced this or have a solution?
I was stuck on this for a while, and found out that my wrapping div had to have { position: relative }.
Does anybody know how to have :hover css work with this solution? Perhaps referring the answer put in the fiddle?
C
Claudio

You can't make the div a link itself, but you can make an <a> tag act as a block, the same behaviour a <div> has.

a {
    display: block;
}

You can then set the width and height on it.


However, this doesn't make a 'div' into a link. It makes a link into a block element. It's a bit different.
This is solution of your problem. Because you can modify div can be clicked like hyperlink, but you can't set cursor(=hand) for display in all browser(only IE support it!).
jjnguy: How? I dislike having lots of content in a link, but this could just as well be part of a navigation menu or something like that. An anchor element () doesn't necessarily have to be plain text, does it? In which way is it wrong to make it into a block? It's semantically correct and it can be used to display it as you want.
This is a perfectly valid solution to a vague question. You actually COULD simply wrap an anchor element around a div, but that would be semantically incorrect. (Block element within inline element).
jjnguy: This is pretty common practice. I'm not saying replace divs with links, but by the sounds of the question he just wanted a block he could click like a button or something.
a
aelsheikh

This is an ancient question, but I thought I'd answer it since everyone here has some crazy solutions. It's actually very very simple...

An anchor tag works like this -

<a href="whatever you want"> EVERYTHING IN HERE TURNS INTO A LINK </a>

Sooo...

<a href="whatever you want"> <div id="thediv" /> </a>

Although I'm not sure if this is valid. If that's the reasoning behind spoken solutions, then I apologise...


It's valid HTML as long as the <div> doesn't contain any interactive content (other <a> elements, <button> elements, etc.).
Your example is not valid HTML - block element contained in an inline element - unless you're using HTML5, which has made an exception for links.
This is a bad example, because what the a tag does is takes all the text in a div and underlines it... this can be mitigated with styling, but the top answer is better.
a #thediv{font-weight:normal;text-decoration:none;} is all you need style-wise.
Tried this and it worked, however it broke the element's positioning. Yes doctype is HTML5 in Chrome (some 2014 version)..
j
jjnguy

Requires a little javascript. But, your div would be clickable.

<div onclick="location.href='http://www.example.com';" style="cursor:pointer;"></div>

Results in bad semantics on the page though, so I'd avoid this one even though it is technically possible.
I thought about using this solution, but it's kind of ugly. I like the solutions involving display: block better.
This looks like a link, but isn't a real link. It has severe usability and accesibility issues, and is a really nasty solution.
Best solution. We just need to run script and send "this" to it.
If they don't have js enabled you lost functionality. As well as being bad for SEO.
M
MagTun

This option doesn’t require an empty.gif as in the most upvoted answer:

HTML:

 <div class="feature">
       <a href="http://www.example.com"></a>
 </div>

CSS:

 div.feature {
        position: relative;
    }

    div.feature a {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        text-decoration: none; /* No underlines on the link */
        z-index: 10; /* Places the link above everything else in the div */
        background-color: #FFF; /* Fix to make div clickable in IE */
        opacity: 0; /* Fix to make div clickable in IE */
        filter: alpha(opacity=1); /* Fix to make div clickable in IE */
    }

As proposed at http://www.digitalskydesign.com/how-to-make-an-entire-div-a-link-using-css/


Thanks! Chris Jumonville's solution is working great on both Andriod and iPhone. Example: gastateparks.org/specials
Shouldn't it be div.feature > a just in case the "everything else" part also contains a link hidden deep within?
this should be the choosen answer, works with bootstrap too
This works beautifully, very smooth, works with screen readers nicely too, HTML5 adhering, works even if you do transforms on the parent object, and inherently makes the cursor into a pointer (as you expect for a clickable object)
C
Calvin

This is a "valid" solution to achieving what you want.

<style type="text/css">
.myspan {
    display: block;
}
</style>
<a href="#"><span class="myspan">text</span></a>

But most-likely what you really want is to have an <a> tag displayed as a block level element.

I would not advise using JavaScript to simulate a hyperlink as that defeats the purpose of markup validation, which is ultimately to promote accessibility (publishing well-formed documents following proper semantic rules minimizes the possibility the same document will be interpreted differently by different browsers).

It would be preferable to publish a web page that does not validate, but renders and functions properly on all browsers, including ones with JavaScript disabled. Furthermore, using onclick does not provide the semantic information for a screen reader to determine that the div is functioning as a link.


N
Noah

The cleanest way would be to use jQuery with the data-tags introduced in HTML. With this solution you can create a link on every tag you want. First define the tag (e.g. div) with a data-link tag:

<div data-link="http://www.google.at/">Some content in the div which is arbitrary</div>

Now you can style the div however you want. And you have to create also the style for the "link"-alike behavior:

[data-link] {
  cursor: pointer;
}

And at last put this jQuery call to the page:

$(document).ready(function() {
  $("[data-link]").click(function() {
    window.location.href = $(this).attr("data-link");
    return false;
  });
});

With this code jQuery applys a click listener to every tag on the page which has a "data-link" attribute and redirects to the URL which is in the data-link attribute.


To get info about data-attributes see: ejohn.org/blog/html-5-data-attributes
a
azro

Not sure if this is valid but it worked for me.

The code :

Whatever


I have to say that this approach is as clean as a css class on your stylesheet. as far as i am concerned, this is the correct and most easy solution.
This is the best one
a
animuson

To make thepeer's answer work in IE 7 and forward, it needs a few tweaks.

IE will not honour z-index if the element is has no background-color, so the link will not overlap parts of the containig div that has content, only the blank parts. To fix this a background is added with opacity 0. For some reason IE7 and various compatibility modes completely fail when using the span in a link approach. However if the link itself is given the style it works just fine.

.blockLink  
{  
    position:absolute;  
    top:0;  
    left: 0;  
    width:100%;  
    height:100%;  
    z-index: 1;  
    background-color:#ffffff;   
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";  
    filter: alpha(opacity=0);  
    opacity:0;  
}
<div style="position:relative">  
    <some content>  
    <a href="somepage" class="blockLink" />  
<div>

w
wdonayredroid

you could also try by wrapping an anchor, then turning its height and width to be the same with its parent. This works for me perfectly.

<div id="css_ID">
    <a href="http://www.your_link.com" style="display:block; height:100%; width:100%;"></a>
</div>

You might also want to make sure the parent div has zero padding and that the tag has zero margin.
V
Vamsi Pavan Mahesh

why not? use <a href="bla"> <div></div> </a> works fine in HTML5


It won't pass HTML validation. Line item cannot store block items.
I mean, that <div><span></span></div> is valid and <span><div></div></span> is not. You shouldn't put display: inline; type of items into display: block; items. The <a> tag is inline box.
Yeah, it can work, because You can do it in multiple ways (better or worse). This particular solution is not good cause the older HTML validation :).
Does it matter that "older HTML validation" does not pass this? It is allowed now, html5 and for a reason so why not use it? I think this solution is fine (it does often require the removal of underline to the div content but still).
@Todilo Because while <a><div></div></a> is valid and works, <a><div><a></a></div></a> is not valid and doesn't work.
J
Jeff Schwarting

This worked for me:

HTML:

<div>

  WHATEVER YOU WANT

  <a href="YOUR LINK HERE">
    <span class="span-link"></span>
  </a>

</div>

CSS:

.span-link {
  position:absolute;
  width:100%;
  height:100%;
  top:0;
  left: 0;
  z-index: 9999;
}

This adds an invisible element (the span), which covers your entire div, and is above your whole div on the z-index, so when someone clicks on that div, the click is essentially intercepted by your invisible "span" layer, which is linked.

Note: If you're already using z-indexes for other elements, just make sure the value of this z-index is higher than anything you want it to rest "on top" of.


Worked for me. Just don't forget to relatively position the parent element.
S
Shankar Narayana Damodaran

This post is Old I know but I just had to fix the same issue because simply writing a normal link tag with the display set to block does not make the whole div clickable in IE. so to fix this issue far simpler than having to use JQuery.

Firstly let us understand why this happens: IE wont make an empty div clickable it only make the text/image within that div/a tag clickable.

Solution: Fill the div with a bakground image and hide it from the viewer.

How? You ask good questions, now listen up. add this backround style to the a tag

> "background:url('some_small_image_path')
> -2000px -2000px no-repeat;"

And there you have it the whole div is now clickable. This was the best way for me cause Im using it for my Photo Gallery to let the user clik on one half of the image to move left/right and then place a small image as well just for visual effects. so for me I used the left and right images as background images anyway!


Thanks! I needed to simulate an imagemap with empty anchors over an image and IE would only let you click if there was content. This fixed it.
J
Justin

Just have the link in the block and enhance it with jquery. It degrades 100% gracefully for anyone without javascript. Doing this with html isn't really the best solution imho. For example:

<div id="div_link">
<h2><a href="mylink.htm">The Link and Headline</a></h2>
<p>Some more stuff and maybe another <a href="mylink.htm">link</a>.</p>
</div>

Then use jquery to make the block clickable (via web designer wall):

$(document).ready(function(){

    $("#div_link").click(function(){
      window.location=$(this).find("a").attr("href"); return false;
    });

});

Then all you have to do is add cursor styles to the div

    #div_link:hover {cursor: pointer;}

For bonus points only apply these styles if javascript is enabled by adding a 'js_enabled' class to the div, or the body, or whatever.


i want to use this but i have 2 links in the div... how can i modify it to be able click on both links? (it currently takes me to "mylink.html" if i click the second link as well..)
j
joan16v

This example worked for me:

<div style="position: relative; width:191px; height:83px;">
    <a href="link.php" style="display:block; width:100%; height:100%;"></a>
</div>

j
jojojohn

This is the best way to do it as used on the BBC website and the Guardian:

I found the technique here: http://codepen.io/IschaGast/pen/Qjxpxo

heres the html

<div class="highlight block-link">
      <h2>I am an example header</h2>
      <p><a href="pageone" class="block-link__overlay-link">This entire box</a> links somewhere, thanks to faux block links. I am some example text with a <a href="pagetwo">custom link</a> that sits within the block</p>

</div>

heres the CSS

/**
 * Block Link
 *
 * A Faux block-level link. Used for when you need a block-level link with
 * clickable areas within it as directly nesting a tags breaks things.
 */


.block-link {
    position: relative;
}

.block-link a {
  position: relative;
  z-index: 1;
}

.block-link .block-link__overlay-link {
    position: static;
    &:before {
      bottom: 0;
      content: "";
      left: 0;
      overflow: hidden;
      position: absolute;
      right: 0;
      top: 0;
      white-space: nowrap;
      z-index: 0;
    }
    &:hover,
    &:focus {
      &:before {
        background: rgba(255,255,0, .2);
      }
    }
}

P
Phillip Chaffee
<a href="…" style="cursor: pointer;"><div> … </div></a>

H
Hbirjand

Actually you need to include the JavaScript code at the moment, check this tutorial to do so.

but there is a tricky way to achieve this using a CSS code you must nest an anchor tag inside your div tag and you must apply this property to it,

display:block;

when you've done that,it will make the whole width area clickable (but within the height of the anchor tag),if you want to cover the whole div area you must set the height of the anchor tag exactly to the height of the div tag,for example:

height:60px;

this is gonna make the whole area clickable,then you can apply text-indent:-9999px to anchor tag to achieve the goal.

this is really tricky and simple and it's just created using CSS code.

here is an example: http://jsfiddle.net/hbirjand/RG8wW/


D
DejanR

This work for me:

<div onclick="location.href='page.html';"  style="cursor:pointer;">...</div>

S
Swarnamayee Mallia

You can give a link to your div by following method:

<div class="boxdiv" onClick="window.location.href='https://www.google.co.in/'">google</div>
<style type="text/css">
.boxdiv {
    cursor:pointer;
    width:200px;
    height:200px;
    background-color:#FF0000;
    color:#fff;
    text-align:center;
    font:13px/17px Arial, Helvetica, sans-serif;
    }
</style>

T
THE AMAZING

You can make surround the element with a href tags or you can use jquery and use

$('').click(function(e){
e.preventDefault();
//DO SOMETHING
});

C
Claudio

This is the simplest way.

Say, this is the div block I want to make clickable:

<div class="inner_headL"></div>

So put a href as follows:

<a href="#">
 <div class="inner_headL"></div>
</a>

Just consider the div block as a normal html element and enable the usual a href tag.
It works on FF at least.


H
Hari

I pulled in a variable because some values in my link will change depending on what record the user is coming from. This worked for testing :

   <div onclick="location.href='page.html';"  style="cursor:pointer;">...</div> 

and this works too :

   <div onclick="location.href='<%=Webpage%>';"  style="cursor:pointer;">...</div> 

code doesn't show for some reason I used the onclick with a jsp variable inside to create a dynamic link
h
halfer

While I don't recommend doing this under any circumstance, here is some code that makes a DIV into a link (note: this example uses jQuery and certain markup is removed for simplicity):

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
    $("div[href]").click(function () {
        window.location = $(this).attr("href");
    });
});

</script>
<div href="http://www.google.com">
     My Div Link
</div>

Again, this is a functional solution, but not really in the spirit of the original question which was for an XHTML solution. While not a huge deal, your answer does start to add noise to the question.
s
saran

Enclosing your div inside an anchor tag <a href></a> works like charm:

    <a href="">
      <div>anything goes here will turn into a link</div>
    </a>

H
Hailei

My smarty pants answer:

"Evasive answer to: "How to make block level element a hyperlink and validate in XHTML 1.1"

Just use HTML5 DOCTYPE DTD."

Didn't actually hold true for ie7

onclick="location.href='page.html';"

Works IE7-9, Chrome, Safari, Firefox,


he was looking for "I am looking for an XHTML 1.1 valid way"
p
philipp

if just everything could be this simple...

#logo {background:url(../global_images/csg-4b15a4b83d966.png) no-repeat top left;background-position:0 -825px;float:left;height:48px;position:relative;width:112px}

#logo a {padding-top:48px; display:block;}



<div id="logo"><a href="../../index.html"></a></div>

just think a little outside the box ;-)