{"id":375761,"date":"2022-12-19T06:58:00","date_gmt":"2022-12-19T14:58:00","guid":{"rendered":"https:\/\/css-tricks.com\/?page_id=375761"},"modified":"2023-01-17T06:03:31","modified_gmt":"2023-01-17T14:03:31","slug":"has","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/almanac\/selectors\/h\/has\/","title":{"rendered":":has()"},"content":{"rendered":"\n

The CSS :has()<\/code> pseudo-class selects elements that contain other elements that match the selector passed into its arguments. It’s often referred to as “the parent selector” because of its ability to select a parent element based on the child elements it contains and apply styles to the parent.<\/p>\n\n\n\n

\/* Select the .card element when it \n   contains a <figure> immediately\n   followed by a paragraph. *\/\n.card:has(figure + p) {\n  flex-direction: row;\n}<\/code><\/pre>\n\n\n\n

This example selects an element with the .card<\/code> class when it contains a <figure><\/code> element that is immediately followed by a <p><\/code> element:<\/p>\n\n\n\n

<article class=\"card\">\n  <figure><\/figure>\n  <p><\/p>\n<\/article><\/code><\/pre>\n\n\n\n

This is incredibly useful to write styles for components that may or may not contain certain elements inside, such as a card grid where a card item always has a paragraph, but might not have an image that accompanies it.<\/p>\n\n\n\n

\"\"
Image or no image? That is the question.<\/figcaption><\/figure>\n\n\n\n

That way, in situations where you do not always know what the markup includes, you can still write styles that match those conditions.<\/p>\n\n\n\n

:has()<\/code> is defined in the Selectors Level 4 specification<\/a> where it is described as “the relational pseudo-class” because of its ability to match selectors based on an element’s relationship to other elements.<\/p>\n\n\n\n\n\n\n

Basic usage<\/h3>\n\n\n

The following HTML contains two <button><\/code> elements. One of them has an SVG icon.<\/p>\n\n\n\n

<!-- Plain button -->\n<button>Add<\/button>\n\n<!-- Button with SVG icon -->\n<button>\n  <svg><\/svg>\n  Add\n<\/button><\/code><\/pre>\n\n\n\n

Now, let\u2019s say, you want to apply styles only to the <button><\/code> that has an <svg><\/code> element inside of it.<\/p>\n\n\n\n

:has()<\/code> is perfectly suited for the job:<\/p>\n\n\n\n

button:has(svg) {\n  \/* Styles *\/\n}<\/code><\/pre>\n\n\n\n

The :has()<\/code> selector gives us the ability to distinguish between a button that has <\/em>a descendant <svg><\/code>, and one that doesn\u2019t.<\/p>\n\n\n\n