More Than Five
More Than Five

Reputation: 10429

Why is only the text clickable in this div?

I am trying to create a div that is a button by putting an anchor inside a div.

HTML

<div class="div1" style="width:300px;">
    <a href="#">hello</a>                        
</div>

CSS

.div1 {
    background-color:red;
    color:white;
    margin:5px;
    border-width:5px;
    border-style:solid;
    padding:10px;
    border-radius:5px;
    text-align:center;
    background: #494949 !important;
}

JSFiddle: http://jsfiddle.net/BzFyS/

I think it is not working because osomething simple I am missing with positioning. Any tips?

Thanks

Upvotes: 0

Views: 4631

Answers (5)

Grapho
Grapho

Reputation: 1654

I am assuming you want this div to be a "button" yes?

The simple solution is to define the size of the <a> by using padding and display: block;

you can still define the colors, margins, and position of the <div>... but the clickable area is in the <a>

Upvotes: 0

Michael
Michael

Reputation: 16142

Try to add to your CSS:

.div1 a {
    display: block;
}

Upvotes: 1

amiry jd
amiry jd

Reputation: 27593

The simplest way: add this css:

.div1 a {
    display: block;
}

That's it.

If you want the whole div be clickable (including the padding area):

.div1 {
    background-color:red;
    color:white;
    margin:5px;
    border-width:5px;
    border-style:solid;
    padding:0px; /* set to 0 */
    border-radius:5px;
    text-align:center;
    background: #494949 !important;
}
.div1 a {
    display: block;
    padding:10px;
}

Demo: http://jsfiddle.net/BzFyS/2/

Upvotes: 3

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382404

If you want the whole div to be clickable, you may do this :

HTML

<div id="div1" style="width:300px;">
    <a href="#">hello</a>                        
</div>

CSS

#div1 {
    background-color:red;
    color:white;
    margin:5px;
    border-width:5px;
    border-style:solid;
    padding:10px;
    border-radius:5px;
    text-align:center;
    background: #494949 !important; /* do you really need that ? */
    cursor: pointer;
}

JavaScript

document.getElementById('div1').onclick=function(){
      // do something
}

But then you don't really need the a element.

Demonstration

Upvotes: 2

Tom Doe
Tom Doe

Reputation: 329

You have to put the tags around the div like this:

<a href="#"><div class="div1" style="width:300px;">
    <p>hello</p>                    
</div></a> 

This will work.

Upvotes: 0

Related Questions