1

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()?

Pedro Gimeno
  • 2,837
  • 1
  • 25
  • 33
  • 1
    Does this answer your question? [Is there a CSS parent selector?](https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – Brewal Dec 27 '22 at 10:43
  • 1
    I don't see how it does. Basically the answers are "use `:has()`" or "use JavaScript/JQuery" or "use `:focus-within`", neither of which helps in this case. – Pedro Gimeno Dec 27 '22 at 10:52
  • There are no more other cases, if you can't use one of the suggested ways then you have to use Javascript. If it is a button, you shouldn't abuse a checkbox for this. – cloned Dec 27 '22 at 10:56
  • @cloned What elements other than a checkbox or a radio can store a state independently of all other elements? (and I really don't like to use a radio for this) – Pedro Gimeno Dec 27 '22 at 11:19
  • @cloned What is the reason you advice to not use checkboxes as css buttons ? – Cédric Dec 27 '22 at 11:31
  • puerly semantic reasons. If it is a button, it should be a ` – cloned Dec 27 '22 at 12:19
  • @PedroGimeno what you are trying to do works with `:has`. As always, if you are not happy with the browsers support, you can use javascript for this task. It's an alternative. You can indeed change your html (answer bellow), but it does not answer the original question where the "button is located inside the box itself". That's why for me it was a duplicate ! Happy you found a workaround by your own though :) – Brewal Dec 28 '22 at 15:33
  • @Brewal *"works with `:has`"* - Doesn't work for me with Firefox 102. *"you can use javascript"* - javascript could be a fallback, but my application is required to work with JS disabled. @cloned has a point about accessibility, though, so I've opened an issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1807670 – Pedro Gimeno Jan 02 '23 at 11:02

1 Answers1

2

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).

Pedro Gimeno
  • 2,837
  • 1
  • 25
  • 33