Making a div a link

Hi,

just wondering is this the correct way to make a div a link

#link {
	height: 40px;
	width: 170px;
	float: left;
}
<a href="http://www.google.com/"><div id="link"></div></a>

hi, i just tried that but it doesnt seem to work as a link :frowning:

Khan was kinda on the right track, but let’s tweak that (divs are already blocks and anchors are inlines (so don’t accept your height or width) until you say otherwise):

<div id=“link”><a href=“http://www.google.com/”></a></div>

#link a {
display: block;
height: 40px;
width: 170px;
}

You don’t necessarily even need the div, unless you’re putting this link someplace where an inline may not go alone (such as a direct child of the body).

So for example, if an anchor can be where you want it, legally, then you can just float the sucker:
<a id=“link” href=“google…”></a>

#link {
float: left; //also puts the anchor into “block context” yay
set width;
set height;
}
(if you don’t set height or width, floats shrink-wrap their dimensions to the content, which in this case you have no anchor text)

You can then float the div or whatever you want for better placement.

If you want the link to grow and shrink with the div (in case your div is not set height or width, or is but may change) you can also use absolute positioning (special cases though, be careful with this one):

<div id=“link”><a href=“http://www.google.com/”></a></div>

#link {
position: relative; //make div a “positioned ancestor” for the anchor
}
#link a {
position: absolute; //also puts the anchor into “block context” yay
height: 100%; //of its positioned parent
width: 100%; //of its positioned parent

//you may also want to add coordinates:
left: 0;
top: 0;
}
(if you don’t set height or width, absolutely-positioned elements shrink-wrap their dimensions to the content, which in this case you have no anchor text)

Often coords are redundant if the positioned element is the first child of the div, because the default is 0, 0. But if there are other things in the div who come first, then for cross-browser compliance, you’ll want to set left and top coords explicitly to 0.

It’s not W3C valid, how about something like this


#link {
    height: 40px;
    width: 170px;
    float: left;
    display: block;
}


<div id="link"><a href="http://www.google.com/"></a></div>