htmlcsscss-selectors

Faking the :has() "parent selector" using only CSS


It's long been hailed as the answer to many selector problems, even disputed by some as entirely unnecessary, but the Selectors Level 4 pseudo-class :has(), better known as the parent selector, is the only one from Level 4 that will not be implemented in CSS, according to the latest revision of the W3 Spec. Reason being that it's inefficient and already covered by JavaScript functionality.

Mulling over this, I've been thinking of how to fake this effect using pure CSS. Below I've provided one method, Q&A style, for achieving the effect as an answer, but would like to know if there are other methods. Specifically, more efficient CSS implementations, or responsive CSS implementations.


Solution

  • In Gecko and WebKit, certain selectors can “jump” using <label for> and an associated <input> element positioned anywhere. This works unreliably, but is still kind of fun.

    #before {
        left: -9999px;
        position: absolute;
    }
    #parent {
        padding: 0.5em;
    }
    #before:hover + #parent {
        background-color: #123;
        color: white;
    }
    #label {
        border: 0.1em solid #678;
        border-radius: 0.2em;
        display: inline-block;
        padding: 0.5em;
    }
    <input type="checkbox" id="before">
    
    <div id="parent">
        <label for="before" id="label">Hover over me!</label>
    </div>

    (You might have to click once if using Chrome.)