Describe the `:has()` pseudo-class (Parent selector)
Jul 15, 2025 am 12:32 AMThe :has() pseudo-class in CSS allows targeting a parent element based on its child elements. It works by using the syntax parent:has(child-selector) to apply styles conditionally. For example, div:has(img) applies styles to a div containing an image. Multiple selectors can be used with commas like div:has(img, p.special). Common use cases include styling containers, form validation feedback, and indicating menu items with submenus. Browser support is available in modern browsers like Chrome, Safari, and Edge, though Firefox lacks support as of late 2024. Considerations include performance impact, non-dynamic behavior, and the need for fallbacks in unsupported environments.
The :has()
pseudo-class is a powerful CSS selector that allows you to target a parent element based on the presence of specific child elements or conditions within it. Before :has()
was introduced, there was no native way in CSS to select a parent based on its children — developers had to rely on JavaScript or add extra classes manually. Now, with :has()
, this becomes possible using just CSS.

How to Use :has()
in CSS
:has()
works by taking a selector as an argument and matching any element that contains at least one matching element inside it. The syntax looks like:
parent:has(child-selector) { /* styles */ }
For example, if you want to style a <div>
only when it contains an <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175251076578590.jpeg" class="lazy" alt="Describe the `:has()` pseudo-class (Parent selector)" >
, you can write:

div:has(img) { border: 2px solid green; }
This will apply the border only to those div
elements that directly contain an image tag somewhere inside them.
You can also chain multiple selectors inside :has()
using commas, like:

div:has(img, p.special) { background-color: #f0f0f0; }
This rule will match any div
that has both an img
and a p
with class special
.
Common Use Cases for :has()
- Styling containers conditionally: For example, applying different padding or margins to a card layout only when it includes a video.
- Form validation feedback: Highlighting a form group when a required input is invalid.
- Menu items with submenus: Applying arrows or indicators only to menu items that have nested lists.
Here's a real-world example:
li:has(ul) { position: relative; padding-right: 20px; } li:has(ul)::after { content: ' ?'; position: absolute; right: 5px; }
This adds a dropdown indicator to any list item that contains a submenu (<ul></ul>
), making your navigation UI more intuitive without adding extra markup.
Browser Support and Considerations
As of now, :has()
is supported in most modern browsers like Chrome (v105 ), Safari (v15.4 ), and Edge (v106 ). Firefox support is still pending as of late 2024, so it’s important to check compatibility if you're targeting a broad audience.
Also, keep in mind:
-
:has()
can affect performance if used excessively or with complex selectors. - It's not dynamic in the same way JavaScript is — it only evaluates at render time.
- Avoid using it in critical layouts unless fallbacks are in place for unsupported browsers.
If you're using it in production, consider feature detection or progressive enhancement strategies to ensure your site remains usable everywhere.
Basically, :has()
gives CSS a long-missing tool for conditional styling based on structure. While it’s not yet universally supported, it's definitely worth experimenting with and planning for future use.
The above is the detailed content of Describe the `:has()` pseudo-class (Parent selector). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

accent-color is an attribute used in CSS to customize the highlight colors of form elements such as checkboxes, radio buttons and sliders; 1. It directly changes the default color of the selected state of the form control, such as changing the blue check mark of the checkbox to red; 2. Supported elements include input boxes of type="checkbox", type="radio" and type="range"; 3. Using accent-color can avoid complex custom styles and extra DOM structures, and maintain native accessibility; 4. It is generally supported by modern browsers, and old browsers need to be downgraded; 5. Set accent-col

InstallDartSassvianpmafterinstallingNode.jsusingnpminstall-gsass.2.CompileSCSStoCSSusingthecommandsassinput.scssoutput.css.3.Usesass--watchinput.scssoutput.csstoauto-compileonsave.4.Watchentirefolderswithsass--watchscss:css.5.Usepartialswith_prefixfo

To change the text color in CSS, you need to use the color attribute; 1. Use the color attribute to set the text foreground color, supporting color names (such as red), hexadecimal codes (such as #ff0000), RGB values (such as rgb(255,0,0)), HSL values (such as hsl(0,100%,50%)), and RGBA or HSLA with transparency (such as rgba(255,0,0,0.5)); 2. You can apply colors to any element containing text, such as h1 to h6 titles, paragraph p, link a (note the color settings of different states of a:link, a:visited, a:hover, a:active), buttons, div, span, etc.; 3. Most

CSStransitionsenablesmoothpropertychangeswithminimalcode,idealforhovereffectsandinteractivefeedback.1.Usethesyntaxtransition:propertydurationtiming-functiondelay;todefinetransitions,liketransition:background-color0.3sease0.1s;.2.Specifytransition-pro

UseautomatedtoolslikePurgeCSSorUnCSStoscanandremoveunusedCSS;2.IntegratepurgingintoyourbuildprocessviaWebpack,Vite,orTailwind’scontentconfiguration;3.AuditCSSusagewithChromeDevToolsCoveragetabbeforepurgingtoavoidremovingneededstyles;4.Safelistdynamic

Backdrop-filter is used to apply visual effects to the content behind the elements. 1. Use backdrop-filter:blur(10px) and other syntax to achieve the frosted glass effect; 2. Supports multiple filter functions such as blur, brightness, contrast, etc. and can be superimposed; 3. It is often used in glass card design, and it is necessary to ensure that the elements overlap with the background; 4. Modern browsers have good support, and @supports can be used to provide downgrade solutions; 5. Avoid excessive blur values and frequent redrawing to optimize performance. This attribute only takes effect when there is content behind the elements.

Astackingcontextisaself-containedlayerinCSSthatcontrolsthez-orderofoverlappingelements,wherenestedcontextsrestrictz-indexinteractions;itiscreatedbypropertieslikez-indexonpositionedelements,opacity

In web development, the choice of CSS units depends on design requirements and responsive performance. 1. Pixels (px) are used to fix sizes such as borders and icons, but are not conducive to responsive design; 2. Percentage (%) is adjusted according to the parent container, suitable for streaming layout but attention to context dependence; 3.em is based on the current font size, rem is based on the root element font, suitable for elastic fonts and unified theme control; 4. Viewport units (vw/vh/vmin/vmax) are adjusted according to the screen size, suitable for full-screen elements and dynamic UI; 5. Auto, inherit, initial and other values are used to automatically calculate, inherit or reset styles, which helps to flexibly layout and style management. The rational use of these units can improve page flexibility and responsiveness.
