Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-browser alternative to CSS :has pseudo-class

I am looking for a cross-browser compatible CSS selector to prevent body scrolling when a modal is opened.

Currently, I am using the CSS :has pseudo-class with the selector:

body:has(dialog.active) {
  /* prevent scroll stuff*/
}

EDIT: has is cross-browser now

like image 772
Marces Avatar asked Dec 07 '25 16:12

Marces


2 Answers

If there was an alternative selector which could achieve the same result, then why would we need :has? There is no alternative selector.

The way we’ve displayed dialogs in the past is to cover the screen with a fixed positioned, partially transparent <div>, then have the dialog appear inside that, or in front of that. This can prevent people clicking on the page behind the dialog. Not sure if it can prevent scrolling — I’ve not looked into that.

My recommendation is to use :has anyway. Firefox will add support eventually, and in the meantime your webpage will still be usable in Firefox, just not as usable as you’d like it to be. Firefox’s market share is only 3%.

Update 2024

All major browsers now support :has.

like image 89
Brett Donald Avatar answered Dec 11 '25 22:12

Brett Donald


Support for :has is available from Firefox 120 version nightly build and soon will be available for use. Here is the test link

https://wpt.fyi/results/css/selectors/dir-pseudo-in-has.html?label=master&label=experimental&aligned&q=label%3Ainterop-2023-pseudos

Here is the official release notes from Firefox Nightly 120.0a1, you can find note part of Web platform section(#3).

https://www.mozilla.org/en-US/firefox/120.0a1/releasenotes/

Starting with Firefox 119, the :has() selector is now available in nightly builds. This allows authors to match elements that has, or "anchors", at least one element matching its relative selector.

like image 38
Suryateja Hanumandla Avatar answered Dec 11 '25 22:12

Suryateja Hanumandla



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!