search

Home  >  Q&A  >  body text

Is it possible to detect element visibility in CSS?

<p>I looked through the API, looking for some pseudo-selectors such as <code>:visible</code> or <code>:hidden</code>, but was disappointed to find that no such selector existed. Since jQuery has supported these selectors for a while, I hope they will be implemented. My idea is that I only want to show a specific element when the element next to it is hidden, but I don't want to use JavaScript to do that. Are there any options? </p>
P粉316423089P粉316423089467 days ago560

reply all(2)I'll reply

  • P粉043566314

    P粉0435663142023-08-23 16:30:06

    It depends on what you mean by "next to it". You can use Attribute selectors to select elements by visibility. Or choose from here:

    To access an element by visibility, you can use e.g. the substring matching attribute selector asterisk [att*=val]. Assume that the div style is hidden using visibility: hidden;:

    div[style*="hidden"] {
    
    }

    The question now is how to access the "next to it" element. If the element you are trying to target is directly behind a hidden element (within the same parent), use the selector:

    div[style*="hidden"] + span {
    
    }

    If it's before, there's nothing you can do about it, but look for some workarounds in the answers to this question: Is there a "previous sibling" CSS selector?

    reply
    0
  • P粉738248522

    P粉7382485222023-08-23 00:16:25

    No, that's not possible, it's not possible, at least not in a stylesheet.

    Otherwise, you will create an infinite loop:

    element:visible {
      display: none;
    }
    
    The

    element starts out visible, then the selector selects it and hides it, then the selector doesn't apply, it becomes visible again, and so on.

    In JS API, pseudo-class selectors are allowed, such as querySelector. But as far as I know, there is no such thing yet, and it's not possible to implement using only CSS.

    reply
    0
  • Cancelreply