How do I select an element based on the state of another element in the page with CSS?

后端 未结 3 904
醉梦人生
醉梦人生 2020-11-22 15:19

I have elements that can reflect different states, either triggered by the user (:hover, :focus, etc.) or manipulated by the server (data-sta

3条回答
  •  孤街浪徒
    2020-11-22 16:04

    As @easwee has already posted a nice answer , I would not repeat any pseudo-class selectors discussed by him,


    A new pseudo class we have now, in css3 is :target.

    The :target pseudo selector in CSS matches when the hash in the URL and the id of an element are the same.

    (The specific use of :target is to style element which is targeted and curruntly visible on top of the viewport)

    So this can actually be (mis)used, based on user interaction(click specifically), to change other element styles, when used with another pseudo classes or sibling selectors.

    For example: target child of sibling of parent.

    :target section div[data-status=finished] {
      color: red;
    }
    a,
    a:visited {
      text-decoration: none;
      color: #000;
    }
    section {
      border: 1px solid grey;
    }

    Note that it wasn't possible to style parent element, or any other element in the html hierarchy before :target was introduced. It is still new, and doing something like this(selecting another element based on click of another element) is not the reason why :target was designed for.

    Disadvantages:

    1. Targeting elements using target, will require not use too much in a single page or it will make you navigate throughout the page unwantedly.

    2. The style targetted for element remains on it untill the target remains same.

    you can play with this fiddle

提交回复
热议问题