css-has-pseudo
Style elements relative to other elements in CSS
Last updated 4 years ago by alaguna .
CC0-1.0 · Repository · Bugs · Original npm
$ cnpm install css-has-pseudo 
SYNC missed versions from official npm registry.

CSS Has Pseudo

NPM Version Support Chat

CSS Has Pseudo lets you style elements relative to other elements in CSS, following the Selectors Level 4 specification.

'Can I use' table

a:has(> img) {
  /* style links that contain an image */
}

h1:has(+ p) {
  /* style level 1 headings that are followed by a paragraph */
}

section:not(:has(h1, h2, h3, h4, h5, h6)) {
  /* style sections that don’t contain any heading elements */
}

body:has(:focus) {
  /* style the body if it contains a focused element */
}

Usage

From the command line, transform CSS files that use :has selectors:

npx css-has-pseudo SOURCE.css --output TRANSFORMED.css

Next, use your transformed CSS with this script:

<link rel="stylesheet" href="TRANSFORMED.css">
<script src="https://unpkg.com/css-has-pseudo/dist/browser-global.js"></script>
<script>cssHasPseudo(document)</script>

⚠️ Please use a versioned url, like this : https://unpkg.com/css-has-pseudo@3.0.0/dist/browser-global.js Without the version, you might unexpectedly get a new major version of the library with breaking changes.

⚠️ If you were using an older version via a CDN, please update the entire url. The old URL will no longer work in a future release.

That’s it. The script is 765 bytes and works in most browser versions, including Internet Explorer 11. With a Mutation Observer polyfill, the script will work down to Internet Explorer 9.

See README BROWSER for more information.

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;
}

/* becomes */

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>

Current Tags

  • 4.0.2                                ...           latest (3 years ago)

4 Versions

  • 4.0.2                                ...           3 years ago
  • 3.0.4                                ...           4 years ago
  • 3.0.3                                ...           4 years ago
  • 0.10.0                                ...           7 years ago
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (1)
Dev Dependencies (2)
Dependents (0)
None

Copyright 2013 - present © cnpmjs.org