search

Home  >  Q&A  >  body text

Is there a "previous sibling" selector?

<p>The plus selector (<code> </code>) selects the next adjacent sibling element. </p> <p>Is there an equivalent selector for selecting the previous sibling? </p>
P粉615829742P粉615829742498 days ago576

reply all(2)I'll reply

  • P粉742550377

    P粉7425503772023-08-16 12:58:21

    I found a way to style all previous sibling elements (as opposed to ~), depending on your needs.

    Suppose you have a list of links, and when hovering over one of the links, all previous links should turn red. You can do this:

    /* 默认链接颜色为蓝色 */
    .parent a {
      color: blue;
    }
    
    /* 先前的兄弟元素应为红色 */
    .parent:hover a {
      color: red;
    }
    .parent a:hover,
    .parent a:hover ~ a {
      color: blue;
    }
    <div class="parent">
      <a href="#">链接</a>
      <a href="#">链接</a>
      <a href="#">链接</a>
      <a href="#">链接</a>
      <a href="#">链接</a>
    </div>

    reply
    0
  • P粉014293738

    P粉0142937382023-08-16 10:22:08

    No, there is no "previous sibling selector".

    Relevantly, ~ is used for general successor sibling selectors (meaning the element is after this element, but not necessarily immediately after it), and is a CSS3 selector. is used for the next sibling selector, which is CSS2.1.

    See Adjacent Sibling Selectors from Selectors Level 3 and ## from Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification #5.7 Adjacent sibling selector.

    reply
    0
  • Cancelreply