Faking the :has() “parent selector” using only CSS

后端 未结 3 428
囚心锁ツ
囚心锁ツ 2020-12-18 04:04

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()

3条回答
  •  庸人自扰
    2020-12-18 04:18

    JSFiddle Example

    For this method, I created a fixed-position container element of static size, with a single child element inside of it, taking up 200px by 200px.

    Then, I added two absolutely-positioned elements (.glass1 and .glass2) to simulate glass panes ("You can look, but you can't touch"), and I used z-index on them so that they would cover the remaining space of the container element.

    The addition of these glass panes is to simulate the effect of nothing happening unless you hover over the child. Otherwise this method wouldn't imitate parent selector behavior; it would just be a normal :hover implementation.

    At this point, it was just a matter of adding a :hover property to the container that did not affect the area covered by the child element.

    .container {
        background: lavender;
        top: 0;
        left: 0;
        position: absolute;
        width: 600px;
        height: 400px;
        z-index: 0;
        border: 1px solid black;
    }
    .glass1 {
        width: 400px;
        height: 200px;
        position: absolute;
        left: 200px;
        top: 0;
        z-index: 2;
    }
    .glass2 {
        width: 600px;
        height: 200px;
        position: absolute;
        z-index: 3;
        top: 200px;
        left: 0;
    }
    .hover {
        background: lightblue;
        width: 200px;
        height: 200px;
        margin: 0;
        position: absolute;
    }
    .container:hover:not(.hover) {
        background: seagreen;
    }
    Hover over me. Change my parent.

    The obvious problem with this implementation is its static nature and its lack of responsiveness. A more-practiced hand might allow for some measure of responsiveness.

    Edit: More efficient version by ZachSaucier

提交回复
热议问题