Forum Moderators: not2easy

Message Too Old, No Replies

Clickable DIV

         

cssmatt

9:16 pm on Feb 28, 2006 (gmt 0)

10+ Year Member



Ive got a simple div which is a blue box, and i want to make the whole thing clickable, and also so that when the user puts their mouse over the div, it changes backgroun color.

To make the whole thing clickable would i just wrap it up in an anchor tag like such ...

<a>
<div class = "box">
title
</div>
</a>

or is there another way of doing it?

My css currently looks like this ...

.box{
background-color:#99CCFF;
padding: 0 1em 0 1em;
margin: 0 2em 0 2em;
border: 1px solid #000000;
height: 30px;
}

daosmith

2:26 am on Mar 1, 2006 (gmt 0)

10+ Year Member



OK well first-off it's invalid HTML to make a block-level <div> element the child of an inline <a> element. And its not just a matter of semantics: IE (correctly) does not make the div "clickable", although, oddly, Firefox does.

I would suggest actually styling the <a> element such that it is block-level with the appropriate height/width, and then use the :hover pseudo-selector to change the background color of the <a> e.g.

a.box {
display: block;
height: 30px;
width: 30px;
background-color: #ff0000;
}

a.box:hover {
background-color: #0000ff;
}

The advantage of this approach is that it will work in IE (IE only supports the :hover pseudo-selector on <a> elements) without any need for javascript, which comes with its own attendant problems.

One proviso: I'm not quite sure what you mean by "clickable." If it means that clicking on the box does not actually take you to a different page i.e. it is not a link, then using the <a> element in this fashion is semantically bad... if this is the case, you probably should use a <div> element, although you will then need to use javascript to get the mouseover effect , because of IE's flawed :hover implementation.