Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...