Using CSS :has() Function

· 1 min read

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