a href link for entire div in HTML/CSS

Adil picture Adil · Dec 16, 2010 · Viewed 432.4k times · Source

Here is what I am trying to accomplish in HTML/CSS:

I have images in different heights and widths, but they are all under 180x235. So what I want to do is create a div with border and vertical-align: middle them all. I have successfully done that but now I am stuck on how to properly a href link the entire div.

Here is my code:

<div id="parentdivimage" style="position:relative;width:184px;height:235px;border-width:2px;border-color:black;border-style:solid;text-align:center;">
    <div id="childdivimage" style="position:absolute;top:50%;height:62px;margin-top:-31px;">
        <img src="myimage.jpg" height="62" width="180">
    </div>
</div>

Please note that for the sake of copy pasting here easily, the style code is inline.

I read somewhere that I can simply add another parent div on top of the code and then do a href inside that. However, based on some research it won't be valid code.

So to sum it up again, I need the entire div (#parentdivimage) to be a href link.

Answer

Ben picture Ben · Dec 16, 2010

UPDATE 06/10/2014: using div's inside a's is semantically correct in HTML5.

You'll need to choose between the following scenarios:

<a href="http://google.com">
    <div>
        Hello world
    </div>
</a>

which is semantically incorrect, but it will work.

<div style="cursor: pointer;" onclick="window.location='http://google.com';">
    Hello world
</div>

which is semantically correct but it involves using JS.

<a href="http://google.com">
    <span style="display: block;">
        Hello world
    </span>
</a>

which is semantically correct and works as expected but is not a div any more.