Css pseudo-class ":has", does not work with attribute

I would like to leave the div that contains the “I-wish-much-happines” class, which contains the “checkbox” in green, can you do it in pure css please?

<!DOCTYPE html>
<html>
    <head>
        <style>
            .a-lot-of-positivity .I-wish-much-happiness:has(input[type=checkbox]){
                background:green!important;
            }
            .a-lot-of-positivity .I-wish-much-happiness{
                background:blue;
                height:300px;
                width: 300px;
                float:left;
            }
        </style>
    </head>
    <body>
        <div class="a-lot-of-positivity">
            <div class="I-wish-much-happiness">
            </div>
            <div class="I-wish-much-happiness">
                <input type="checkbox" />
            </div>
            <div class="I-wish-much-happiness">
            </div>
        </div>
    </body>
</html>

Does it work if you swap the order of the styles?

The code works as-is. The !important is unnecessary, as the :has psuedoclass is more specific of a rule than the generalized class rule.

I dont know what you mean by “pure CSS”. :has is part of the CSS Selectors-4 Draft, and has been adopted by everything except Firefox (who have adopted, but require you to specifically enable it); !important has been part of CSS since its inception. Both are part of CSS. There is no preprocessing going on of your CSS.

2 Likes

Ye I was about to say the same as @m_hutley . The code is working in Chrome but there is no support in Firefox yet. There is no way in CSS to target the parent like this without using :has.

Technically there is, but you have to go to about:config and turn layout.css.has-selector.enabled to True (it defaults to false).

I assume this is Firefox implementing the draft but waiting for it to be fully out and inplace? shrug

1 Like

Is the checkbox always there in that second sibling or is it a case of only changing the background if the checkbox is present?

Otherwise you could just use nth-child to style the second element but I’m guessing you already know that :slight_smile:

Thanks for the answers, firefox is considered the second browser in the world for having many derivatives and the main competitors are chromium. A very important browser is opening up the market for not having this option active. I’m going to do it differently because of the risk of it not working in firefox and other browsers. Thanks for the responses again.

Just keep in mind that just because Firefox currently defaults to making this false, doesnt mean they wont switch it to true at some point; as speculated, they may be waiting for the CSS Selectors-4 draft to become a full Recommendation before switching it.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.