How to Use CSS :has() Function (Step-by-Step Guide)

This article introduces the use of CSS :has() function, including its advantages, implementation details, and related resources to help improve efficiency with CSS :has() function.

Nov 1, 2023 · 1 min read · 202 Words · -Views -Comments · Programming
CSS Web Development 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Recently while developing WebShell, I encountered a requirement to dynamically adjust styles - when the terminal enables split-screen mode with editor appearing on the top, the terminal at the bottom needs style adjustments, specifically adjusting the minimum height. Considering implementing this with CSS.

Analysis

The :has() function can use CSS selectors to determine whether a certain element exists after or within child descendants. Therefore, using :has() can capture the editor element in split-screen situations, then normally use + to get sibling elements, and actually adjust styles. Of course, JS can also implement this, but CSS implementation is simpler.

Example

    <style>
      .terminal {
        width: 100%;
        min-height: 200px;
        background-color: #4bd58d;
      }
      .editor{
        width: 100%;
        height: 100px;
        background-color: #003dfd;
      }

      .editor:has(+.terminal) +.terminal{
        background-color: #ff0000;
      }
    </style>

Compatibility

When using CSS functions, compatibility should always be considered. The :has() function is currently not supported in Firefox. However, since this functionality is just an enhancement here, compatibility doesn’t need to be considered. If compatibility is needed, consider implementing with JS.

Final Thoughts

CSS functions can to some extent avoid implementation through JS, so they can be utilized more in development. Of course, compatibility also needs to be considered, as compatibility is a major challenge in frontend development.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover