Hide div when clicking the close button with CSS

617 Views Asked by At

In my application I need to have notice/warning/error boxes (DIVs) that the user can close with a button located inside the box itself. A problem I'm facing is that the :has() pseudo-class is not widely supported; otherwise I could do something like this:

.msgbox:has(.closeflag:checked) { display:none; }

(where .msgbox is the external div and .closeflag the checkbox with the close status).

Is there an alternative to do the same without using :has()?

1

There are 1 best solutions below

0
Pedro Gimeno On

I found this solution that gets the job done:

.closeflag {
  display: none;
}

.closebutton {
  float: right;
  cursor: pointer;
}

.closeflag:checked+.msgbox {
  display: none;
}

/* For demonstration purposes: */
.msgbox {
  border: solid 1px maroon;
}
<input class="closeflag" id="unique-id-for-box-1" type="checkbox">
<div class="msgbox">
  <label class="closebutton" for="unique-id-for-box-1">&#10060;</label> text
</div>

Basically, the <label for...> acts as a remote control for the checkbox, which no longer needs to be inside the div (but the label itself is).