You can now select parents in CSS with :has

You can now select parents in CSS with :has

CSS have released a powerful new tool, that gives you lot of new options

Traditionally in CSS, you could only select child items. That have all changed with the :has selection and you can now select parents as well

:has


Traditionally you had to find the child item or item directly and then do something

[snippet]article form input: do something[/snippet]

So if you wanted to only do something on article pages, you had to often write a bit of code to ensure it was done correctly

[snippet]form:has(article) input: do something[/snippet]

Now with :has, you can check if example article exist and if so, do something

Next level


With the use of :has, you can even affect other areas than where you are located

[snippet].content_layout:has(.article-card:hover) .article-card:not(:hover) { filter: brightness(80%); }[/snippet]

Above snippet checks if anyone is hovering .article-card under .content_layout. If true, it will find .article-card's that are not being hovered and lower brightness on them

20221115_1001_6373bdff452f3.webp

An example from our homepage, where we use this exact feature. We dim slight the articles that are not hovered, to better highlight where you are

When :has is not supported


If :has is not supported, the code will not be executed as the browser will not be able to check it

[snippet]#mainContent:has(#frontpage,#article) { padding-top: 40px; }[/snippet]

We use :has on for top padding on mobile devices, to make our logo slight overlap the top image on the frontpage and in articles. All other pages it will just stay on top, without overlapping

20221115_1001_6373bb311d3dd.webp

If the browser do not support :has, the top padding will not be adjusted and there will be spacing between the logon and text. So here we recommend designing with focus first if it's not supported and then add :has on top and then do something. Especially if you plan to support older browsers

Supported browser


:has is a fairly new release, but it's getting quick traction and most major browser already support it, in their latest stable release

BrowserSupported from version
Chrome105+
Edge105+
Safari15.4
FirefoxNot Supported
Opera91+
IENot Supported
Chrome for Android107
Safari on iOS16.1
Samsung InternetNot Supported

Check out Can I Use [↗] for up-to-date browser support



Tags: #CSS #has

We sometimes publish affiliate links and these always needs to follow our editorial policy, for more information check out our affiliate link policy

You might also like

Comments

Sign up or Login to post a comment

There are no comments, be the first to comment.