I have a div
acting as a round button. It is styled so that a significant part of its overall appearance comes from a box-shadow
:
<body style="background:black">
<div id="button" style="width: 50px; height: 50px; background: yellow; border: none; border-radius: 50px; box-shadow: 0 0 0 5px #c03, 0 0 2px 7px #fff"></div>
</body>
I have a click event listener attached to the button div
. Unfortunately, it doesn't respond if the div
is clicked on the box-shadow
as the box-shadow
is rendered outside the div
.
This is particularly a problem on touch devices where the finger sometimes doesn't hit the center of the div
. (Of course, it responds normally if the click is within the div's 50px area.)
Is it possible to make the event listener respond to clicks on the box-shadow
as well as the actual div
?
I realise I can use a separate and larger transparent div over the top of the button and attach the event listener to that, but is such a workaround necessary?
(The button div
must be styled with box-shadow
. I can't use the border
property or increase padding
.)
Yes, changing the
box-shadow
to aninset
shadow will make the area occupied by the shadow also clickable. Aninset
box-shadow is actually added within the element and hence even a click on the shadow is treated as a click on thediv
.The following are some points that need to be considered while changing the shadow to an inset one:
box-shadow
is added inside, the height and width of thediv
should be increased by a bit to make sure the final outcome is the same size as your original version. In the normalbox-shadow
version, the size of the shape would be the container's radius + spread radius.Note: In the above snippet, I have replaced the inline style attribute's contents with CSS.
If you want the second shadow (the white colored one) to blur towards the outside and blend with the body background, you could replace the
box-shadow
withradial-gradient
like in the below sample. But there are two drawbacks of usingradial-gradient
, one is it has lower browser support and second is the curves are not very smooth when the element's size is very small.