search

Home  >  Q&A  >  body text

Is there a "previous sibling" selector?

<p>The plus selector (<code> </code>) selects the next adjacent sibling. </p> <p>Is there an equivalent for the previous sibling? </p>
P粉111627787P粉111627787516 days ago486

reply all(2)I'll reply

  • P粉098979048

    P粉0989790482023-08-24 11:58:20

    I found a way to style all previous siblings (as opposed to ~) that might work depending on your needs.

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

    /* default link color is blue */
    .parent a {
      color: blue;
    }
    
    /* prev siblings should be red */
    .parent:hover a {
      color: red;
    }
    .parent a:hover,
    .parent a:hover ~ a {
      color: blue;
    }
    <div class="parent">
      <a href="#">link</a>
      <a href="#">link</a>
      <a href="#">link</a>
      <a href="#">link</a>
      <a href="#">link</a>
    </div>

    reply
    0
  • P粉044526217

    P粉0445262172023-08-24 10:43:13

    No, there is no "previous sibling" selector.

    Related to this, ~ is used for generic subsequent sibling elements (meaning that the element comes after this element, but not necessarily immediately after it), and is a CSS3 selector. Represents the next sibling, which is CSS2.1.

    SeeAdjacent Sibling Combinators "http://www.w3.org/TR/css3-selectors/" rel="noreferrer">Selector Level 3 and 5.7 Adjacent Sibling Selectors From the Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) specification.

    reply
    0
  • Cancelreply