What is css-has-pseudo?
The css-has-pseudo package is a tool designed to polyfill CSS :has() pseudo-class support in environments where it is not natively available. This package enables developers to use the :has() selector in their CSS, allowing for more complex styling scenarios based on the presence of descendants in the DOM.
What are css-has-pseudo's main functionalities?
Polyfill for :has() pseudo-class
This feature allows developers to use the :has() CSS pseudo-class in environments that do not support it natively. The code sample demonstrates how to import the polyfill and apply a CSS rule using :has() to style an unordered list with a blue border if it contains an 'li' element with the class 'active'.
import 'css-has-pseudo';
// Example CSS using :has()
const style = `
ul:has(> li.active) {
border: 1px solid blue;
}
`;
// Apply styles to document
const styleSheet = document.createElement('style');
styleSheet.innerText = style;
document.head.appendChild(styleSheet);
Other packages similar to css-has-pseudo
postcss-pseudo-class-any-link
This package is a PostCSS plugin to polyfill the :any-link pseudo-class. It is similar to css-has-pseudo in that it provides support for newer CSS features in environments that lack them. However, it focuses on the :any-link pseudo-class rather than :has().
CSS Has Pseudo
CSS Has Pseudo lets you style elements relative to other elements in CSS,
following the Selectors Level 4 specification.
a:has(> img) {
}
h1:has(+ p) {
}
section:not(:has(h1, h2, h3, h4, h5, h6)) {
}
body:has(:focus) {
}
Usage
From the command line, transform CSS files that use :has
selectors:
npx css-has-pseudo SOURCE.css TRANSFORMED.css
Next, use your transformed CSS with this script:
<link rel="stylesheet" href="TRANSFORMED.css">
<script src="https://unpkg.com/css-has-pseudo/browser"></script>
<script>cssHasPseudo(document)</script>
That’s it. The script is 765 bytes and works in all browsers, including
Internet Explorer 11. With a Mutation Observer polyfill, the script will work
down to Internet Explorer 9.
How it works
The PostCSS plugin clones rules containing :has
,
replacing them with an alternative [:has]
selector.
body:has(:focus) {
background-color: yellow;
}
section:not(:has(h1, h2, h3, h4, h5, h6)) {
background-color: gray;
}
body[\:has\(\:focus\)] {
background-color: yellow;
}
body:has(:focus) {
background-color: yellow;
}
section[\:not-has\(h1\,\%20h2\,\%20h3\,\%20h4\,\%20h5\,\%20h6\)] {
background-color: gray;
}
section:not(:has(h1, h2, h3, h4, h5, h6)) {
background-color: gray;
}
Next, the JavaScript library adds a [:has]
attribute to
elements otherwise matching :has
natively.
<body :has(:focus)>
<input value="This element is focused">
</body>