TIL

Expand a button's clickable aree with a pseudo element

If you have a small button and want to give users a bigger area around it to click, you can achieve this with a pseudo element.

  • Make the container element relative positioned
  • Add a :before element to the button
  • Make the :before absolute positioned and set it to cover the entire container (or whatever portion of it you think necessary)
<div>
  <figure>
    <img src="https://placehold.co/600x400" alt="">
    <button>Expand</button>
    <figcaption>A caption for the image. This could be very long or very short. It could even be super long if you really needed it to.</figcaption>
  </figure>
</div>
div {
  max-width: 40rem;
  margin: 0 auto;
}

figure { 
  position: relative;
  display: flex;
  flex-flow: row wrap;
  align-items: flex-start;
  gap: .5rem;
}

figure > img {
  width: 100%;
}

figcaption {
  flex: 1;
  z-index: 1;

  background-color: white; /* only to highlight what's happening */
}

figure button {
  order: 1;
  cursor: pointer;
}

figure button::before {
  position: absolute;
  top: 0;
  left: 0;
  display: block;
  width: 100%;
  height: 100%; /* This could be a calculation */
  opacity: .2;
  background-color: blue;
  content: "";
}