search

Home  >  Q&A  >  body text

Does the "previous sibling element selector" exist?

<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粉054616867P粉054616867511 days ago554

reply all(2)I'll reply

  • P粉447002127

    P粉4470021272023-08-21 12:32:47

    I found a way to style all preceding 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粉957723124

    P粉9577231242023-08-21 10:52:52

    No, there is no "previous sibling" selector.

    On a related note, ~ is used for general subsequent sibling selectors (meaning the element comes after this element, but not necessarily immediately after), which is a CSS3 selector. is for the next sibling selector, which is CSS2.1.

    See Adjacent Sibling Selectors from Selector Level 3 and from of the Cascading Style Sheets Version 2.1 Revision 1 (CSS 2.1) specification #adjacentbrotherscombiner.

    reply
    0
  • Cancelreply