简体   繁体   中英

How do you make the area of a div clickable? Not the whole div!

If you have a background image in a div with a (drawn) button in the middle and some other drawings around it. How do you make the button clickable but not the whole div because I don't want the user to click the drawings around it, if that makes sense!? I am I wasting my time playing with padding and margins? Should I just create two divs? My boss says he has managed to make it using one div before.

Cheers

Try this code:

#container { width:200px; height:100px; position:relative }
#clicker { display:block; width:20px; height:10px; position:absolute; top:20px; left:100px; }

<div id="container">
    <a id="clicker" href="#link"></a>
</div>

Obviously change all dimensions to match the area you want to make clickable.

In short — you don't.

Backgrounds are backgrounds. They aren't content. They aren't interactive.

It is possible to hack around that, but you shouldn't. If you have some content for the user to interact with, then present it as content. Use an <img> .

Put an element which is transparent and relatively positioned inside the div. Position it at the top of the button and make it the same size as the button. Make the element click able.

You could make the div "position: relative" and then place an <a> tag on the drawing using

display: block;
width: your_width;
height: your_height;
position: absolute;
left: your_position_x;
top: your_position_y;

That would be the cleanest way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM