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

后端 未结 3 433
囚心锁ツ
囚心锁ツ 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:20

    This is an example of what I mentioned in comments – instead of the element that gets hovered over actually being a child element, it is a mere sibling that comes right before the element that should be affected – and the adjacent sibling combinator is used to affect the second element on hover of the first one,

    .hover:hover ~ .container {
        background: red;
    }
    

    http://jsfiddle.net/95HKP/5/embedded/result/

    Since it has no need for additional positioned elements “covering up” the second element, it does not suffer from the mentioned drawbacks, such as actual content in the second element not being accessible via mouse cursor for selection or other forms of interaction. Only the “triggering” element itself is positioned absolutely over the other one – instead of using absolute positioning, other methods to achieve that are possible as well, f.e. a negative margin-bottom.
    (And I have introduced a “spacer” element to keep the content from being overlapped by the absolutely positioned element – that does not necessarily need an additional element, for example a pseudo element created using ::before would do as well.)

    So again, this is also not a “parent selector” – just something that achieves a certain effect by using some positioning and other, broadly available selectors.

提交回复
热议问题