Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sensible approach to nested clickable elements

I am implementing a piece of UI where a whole element is clickable, as is a "button" within it.

Basically this (and no, I am not actually using inline event handlers):

<div onclick="alert('outer action')">
  Maybe some text here
  <button onclick="alert('inner action')">Action</button>
</div>

For better or worse, HTML doesn't allow nesting buttons. I'm not too happy about the outer element being a div, because it seems meaningless. I could slap a role="button" on it, but I wonder if there's a better solution at hand.

like image 864
back2dos Avatar asked Mar 06 '26 16:03

back2dos


1 Answers

Make the two buttons siblings in a parent div. Then use CSS to to make the "outer" button fill the whole container.

Add an aria-label to the outer button, so that it's accessible.

.box {
  position: relative;
  display: flex;
  background: #ddd;
}

.box:hover {
  background: #eee;
}

.box > * {
  position: relative;
  padding: 1rem;
}

.outer-button {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: transparent;
  border: none;
}
<div class="box">
  <button class="outer-button" onclick="alert('outer action')" aria-label="Perform outer action"></button>
  <div>Text here</div>
  <button onclick="alert('inner action')">Action</button>
  <div>More content</div>
</div>
like image 188
mfluehr Avatar answered Mar 08 '26 04:03

mfluehr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!