By Jourkey

2009-11-30 04:06:36 8 Comments

The plus sign (+) is for the next sibling.

Is there an equivalent for the previous sibling?


@Ron16 2020-06-05 16:25:53

There isn't, and there is.

If you must place the label before the input, just place the label after the input and keep both the label & the input inside a div, and style the div as following :

.input-box {
  display: flex;
  flex-direction: column-reverse;
<div class="input-box">

   <label for="email" class="form-item-header">                  

Now you can apply the standard next sibling styling options available in css, and it will appear like you are using a previous sibling styling.

@kyle 2019-06-10 01:55:53

I needed a solution to select the previous sibling tr. I came up with this solution using React and Styled-components. This is not my exact solution (This is from memory, hours later). I know there is a flaw in the setHighlighterRow function.

OnMouseOver a row will set the row index to state, and rerender the previous row with a new background color

class ReactClass extends Component {
  constructor() {
    this.state = {
       highlightRowIndex: null

  setHighlightedRow = (index) => {
    const highlightRowIndex = index === null ? null : index - 1;

  render() {
    return (
           {, index) => {
                const isHighlighted = index === this.state.highlightRowIndex
                return {
                        onMouseOver={() => this.setHighlightedRow(index)}
                        onMouseOut={() => this.setHighlightedRow(null)}

const Trow =`
    & td {
        background-color: ${p => p.isHighlighted ? 'red' : 'white'};

    &:hover {
        background-color: red;

@SherylHohman 2019-05-09 07:45:02

No. It is not possible via CSS. It takes the "Cascade" to heart ;-).

However, if you are able to add JavaScript to your page, a little bit of jQuery could get you to your end goal.
You can use jQuery's find to perform a "look-ahead" on your target element/class/id, then backtrack to select your target.
Then you use jQuery to re-write the DOM (CSS) for your element.

Based on this answer by Mike Brant, the following jQuery snippet could help.

$('p + ul').prev('p')

This first selects all <ul>s that immediately follow a <p>.
Then it "backtracks" to select all the previous <p>s from that set of <ul>s.

Effectively, "previous sibling" has been selected via jQuery.
Now, use the .css function to pass in your CSS new values for that element.

In my case I was looking to find a way to select a DIV with the id #full-width, but ONLY if it had a (indirect) descendant DIV with the class of .companies.

I had control of all the HTML under .companies, but could not alter any of the HTML above it.
And the cascade goes only 1 direction: down.

Thus I could select ALL #full-widths.
Or I could select .companies that only followed a #full-width.
But I could not select only #full-widths that proceeded .companies.

And, again, I was unable to add .companies any higher up in the HTML. That part of the HTML was written externally, and wrapped our code.

But with jQuery, I can select the required #full-widths, then assign the appropriate style:

$("#full-width").find(".companies").parents("#full-width").css( "width", "300px" );

This finds all #full-width .companies, and selects just those .companies, similar to how selectors are used to target specific elements in standard in CSS.
Then it uses .parents to "backtrack" and select ALL parents of .companies,
but filters those results to keep only #fill-width elements, so that in the end,
it only selects a #full-width element if it has a .companies class descendant.
Finally, it assigns a new CSS (width) value to the resulting element.

$(".parent").find(".change-parent").parents(".parent").css( "background-color", "darkred");
div {
  background-color: lightblue;
  width: 120px;
  height: 40px;
  border: 1px solid gray;
  padding: 5px;
.wrapper {
  background-color: blue;
  width: 250px;
  height: 165px;
.parent {
  background-color: green;
  width: 200px;
  height: 70px;
<script src=""></script>
<div class="wrapper">

  <div class="parent">
    "parent" turns red
    <div class="change-parent">
    descendant: "change-parent"
  <div class="parent">
    "parent" stays green
    <div class="nope">
    descendant: "nope"
Target <b>"<span style="color:darkgreen">parent</span>"</b> to turn <span style="color:red">red</span>.<br>
<b>Only</b> if it <b>has</b> a descendant of "change-parent".<br>
(reverse cascade, look ahead, parent un-descendant)

jQuery Reference Docs:
$() or jQuery(): DOM element.
.find: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
.parents: Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector (filters the results to only include the listed elements/selectors).
.css: Set one or more CSS properties for the set of matched elements.

@Fabian von Ellerts 2019-07-10 17:43:37

This has nothing to do with the question. Of course it's possible using JS and you don't even need jQuery for this (previousElementSibling).

@SherylHohman 2019-07-10 19:48:39

@FabianvonEllerts I answered OP's question directly in the first line of my response. As my answer states, it is literally not possible via CSS. I then provided 1 possible path forward to achieve the goal, using a technology (JS | JQuery) that users of CSS might be familiar with and have access to. For example, many WordPress sites also have JQuery, so it is an easy entry point: easy to use, remember, and expand upon. It'd be irresponsible to simply answer NO, without providing an alternate way to accomplish the goal. I shared what I learned and used when I had the same question.

@SherylHohman 2019-07-10 19:56:38

previousElementSibling() for those more familiar with native JS DOM functions could provide another non-CSS path forward.

@SherylHohman 2019-07-10 20:16:54

I found the other CSS HACKS very interesting, but for my particular use case they either did not work (fell into the caveats category), or were too convoluted. For others that fall into the same circumstance, it is fair to share this easy-to-use method that can work, where the above solutions fail, or would be too difficult to implement/maintain. Many CSS HACKS were shared. This work around was not covered. NONE of the answers use the + (non-existent) selector that the OP specifically asked for. Consider this answer a JS "hack". It's here to save someone else time I spent to find a solution.

@ruffin 2020-06-18 22:01:38

"It takes the "Cascade" to heart ;-)." Well said. You could probably have stopped right there. ;^D

@Rounin 2017-04-25 09:59:44

+ is for the next sibling. Is there an equivalent for the previous sibling?

You can use the two axe selectors: ! and ?

There are 2 subsequent sibling selectors in conventional CSS:

  • + is the immediate subsequent sibling selector
  • ~ is the any subsequent sibling selector

In conventional CSS, there is no previous sibling selector.

However, in the axe CSS post-processor library, there are 2 previous sibling selectors:

  • ? is the immediate previous sibling selector (opposite of +)
  • ! is the any previous sibling selector (opposite of ~)

Working Example:

In the example below:

  • .any-subsequent:hover ~ div selects any subsequent div
  • .immediate-subsequent:hover + div selects the immediate subsequent div
  • .any-previous:hover ! div selects any previous div
  • .immediate-previous:hover ? div selects the immediate previous div

div {
  display: inline-block;
  width: 60px;
  height: 100px;
  color: rgb(255, 255, 255);
  background-color: rgb(255, 0, 0);
  text-align: center;
  vertical-align: top;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.6s ease-out;

code {
  display: block;
  margin: 4px;
  font-size: 24px;
  line-height: 24px;
  background-color: rgba(0, 0, 0, 0.5);

div:nth-of-type(-n+4) {
  background-color: rgb(0, 0, 255);

div:nth-of-type(n+3):nth-of-type(-n+6) {
  opacity: 1;

.any-subsequent:hover ~ div,
.immediate-subsequent:hover + div,
.any-previous:hover ! div,
.immediate-previous:hover ? div {
  opacity: 1;
<h2>Hover over any of the blocks below</h2>


<div class="immediate-previous">Hover for <code>?</code> selector</div>
<div class="any-previous">Hover for <code>!</code> selector</div>
<div class="any-subsequent">Hover for <code>~</code> selector</div>
<div class="immediate-subsequent">Hover for <code>+</code> selector</div>


<script src=""></script>

@alex 2017-09-05 22:57:39

This give me a syntax error when I try to implement it on sass inside a rails project.

@Rounin 2017-09-06 15:11:52

axe is a CSS post-processor. It does not use the same syntax as CSS pre-processors such as Sass, Less or Stylus.

@Dionys 2020-05-27 00:35:11

@Rounin would you mind adding some documentation links ? I cannot find axe post-processor.

@Rounin 2020-05-27 01:02:43

@Dionys - Thanks for your interest. axe is a project I started in late 2016, when I didn't know ES2015 and even objects in JS were very new to me. The GitHub repository is here: . I very much mean to return to this at some point (I've also developed something called axe-blades which are the CSS equivalent of javascript events), but I need to complete my work on another project (codenamed ashiva) first.

@0x1gene 2014-09-03 16:16:21

There is no official way to do that at the moment but you can use a little trick to achieve this ! Remember that it is experimental and it has some limitation ... (check this link if you worries about navigator compatibility )

What you can do is use a CSS3 selector : the pseudo classe called nth-child()

#list>* {
  display: inline-block;
  padding: 20px 28px;
  margin-right: 5px;
  border: 1px solid #bbb;
  background: #ddd;
  color: #444;
  margin: 0.4em 0;

#list :nth-child(-n+4) {
  color: #600b90;
  border: 1px dashed red;
  background: orange;
<p>The oranges elements are the previous sibling li selected using li:nth-child(-n+4)</p>

<div id="list">
  <span>1</span><!-- this will be selected -->
  <p>2</p><!-- this will be selected -->
  <p>3</p><!-- this will be selected -->
  <div>4</div><!-- this will be selected -->


  • You can't select previous elements based on the classes of the next elements
  • This is the same for pseudo classes

@Ian 2014-10-27 20:13:41

Why do they have to be the same node? Why not just use :nth-child(-n+4)?

@0x1gene 2014-10-28 00:11:50

@Ian because the :nth-child(-n+4) is a pseudo class that needs to be apply to a selector in order to work properly. If you are not convince, try to experiment it using a fork of my fiddle and you'll see that it doesn't wok

@Josh Burgess 2015-01-13 19:07:58

Actually, you can go node-type independent using the * selector, but it's obnoxiously bad practice.

@Jake Cattrall 2015-01-23 14:59:03

This is the answer that worked for me, not sure why it's not voted higher or accepted.

@Jamie Barker 2015-06-01 10:44:13

Actually, it does work for different nodes: Please update your answer :)

@bitoolean 2019-07-11 15:53:03

I had a complex selector, but let's say it's li#someListItem and I wanted the node(s) right before it (which is how I interpret "previous") - I don't see how the information you provided can help me express that through CSS. You're just selecting the first n siblings, and assume I know the n. Based on this logic, any selector might do the trick and select the element(s) I need (such as :not() ).

@corwin.amber 2020-06-29 19:44:11

What? This just selects the first four elements. Not at all what was asked.

@Michael Benjamin 2016-03-20 18:49:34

Consider the order property of flex and grid layouts.

I'll focus on flexbox in the examples below, but the same concepts apply to Grid.

With flexbox, a previous sibling selector can be simulated.

In particular, the flex order property can move elements around the screen.

Here's an example:

You want element A to turn red when element B is hovered.



  1. Make the ul a flex container.

    ul { display: flex; }

  1. Reverse the order of siblings in the mark-up.


  1. Use a sibling selector to target Element A (~ or + will do) .

    li:hover + li { background-color: red; }

  1. Use the flex order property to restore the order of siblings on the visual display.

    li:last-child { order: -1; }

...and voilà! A previous sibling selector is born (or at least simulated).

Here's the full code:

ul {
    display: flex;

li:hover + li {
    background-color: red;

li:last-child {
    order: -1;

/* non-essential decorative styles */
li {
    height: 200px;
    width: 200px;
    background-color: aqua;
    margin: 5px;
    list-style-type: none;
    cursor: pointer;

From the flexbox spec:

5.4. Display Order: the order property

Flex items are, by default, displayed and laid out in the same order as they appear in the source document. The order property can be used to change this ordering.

The order property controls the order in which flex items appear within the flex container, by assigning them to ordinal groups. It takes a single <integer> value, which specifies which ordinal group the flex item belongs to.

The initial order value for all flex items is 0.

Also see order in the CSS Grid Layout spec.

Examples of "previous sibling selectors" created with the flex order property.

.container { display: flex; }

.box5 { order: 1; }    
.box5:hover + .box4 { background-color: orangered; font-size: 1.5em; }

.box6 { order: -4; }
.box7 { order: -3; }
.box8 { order: -2; }
.box9 { order: -1; }
.box9:hover ~ :not(.box12):nth-child(-1n+5) { background-color: orangered;
                                              font-size: 1.5em; }
.box12 { order: 2; }
.box12:hover ~ :nth-last-child(-1n+2) { background-color: orangered;
                                        font-size: 1.5em; }
.box21 { order: 1; }
.box21:hover ~ .box { background-color: orangered; font-size: 1.5em; }

/* non-essential decorative styles */
.container {
    padding: 5px;
    background-color: #888;
.box {
    height: 50px;
    width: 75px;
    margin: 5px;
    background-color: lightgreen;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    cursor: pointer;
Using the flex <code>order</code> property to construct a previous sibling selector

<div class="container">
    <div class="box box1"><span>1</span></div>
    <div class="box box2"><span>2</span></div>
    <div class="box box3"><span>3</span></div>
    <div class="box box5"><span>HOVER ME</span></div>
    <div class="box box4"><span>4</span></div>


<div class="container">
    <div class="box box9"><span>HOVER ME</span></div>
    <div class="box box12"><span>HOVER ME</span></div>
    <div class="box box6"><span>6</span></div>
    <div class="box box7"><span>7</span></div>
    <div class="box box8"><span>8</span></div>
    <div class="box box10"><span>10</span></div>
    <div class="box box11"><span>11</span></div>


<div class="container">
    <div class="box box21"><span>HOVER ME</span></div>
    <div class="box box13"><span>13</span></div>
    <div class="box box14"><span>14</span></div>
    <div class="box box15"><span>15</span></div>
    <div class="box box16"><span>16</span></div>
    <div class="box box17"><span>17</span></div>
    <div class="box box18"><span>18</span></div>
    <div class="box box19"><span>19</span></div>
    <div class="box box20"><span>20</span></div>


A Side Note – Two Outdated Beliefs about CSS

Flexbox is shattering long-held beliefs about CSS.

One such belief is that a previous sibling selector is not possible in CSS.

To say this belief is widespread would be an understatement. Here's a sampling of related questions on Stack Overflow alone:

As described above, this belief is not entirely true. A previous sibling selector can be simulated in CSS using the flex order property.

The z-index Myth

Another long-standing belief has been that z-index works only on positioned elements.

In fact, the most current version of the spec – the W3C Editor's Draft – still asserts this to be true:

9.9.1 Specifying the stack level: the z-index property


  • Value: auto | | inherit
  • Initial: auto
  • Applies to: positioned elements
  • Inherited: no
  • Percentages: N/A
  • Media: visual
  • Computed value: as specified

(emphasis added)

In reality, however, this information is obsolete and inaccurate.

Elements that are flex items or grid items can create stacking contexts even when position is static.

4.3. Flex Item Z-Ordering

Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

5.4. Z-axis Ordering: the z-index property

The painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

Here's a demonstration of z-index working on non-positioned flex items:

@Marat Tanalin 2016-03-20 21:47:02

The order property is not a solution since it is solely intended to change visual order, so it does not restore the original semantical order that you are forced to change in HTML for this workaround to work.

@BoltClock 2016-03-21 04:52:26

@Marat Tanalin: For 90% of use cases, assuming browser support isn't an issue, this will work just fine. The remaining 10% of use cases are either 1) cases where changing the visual order isn't a solution, or 2) cases that don't involve CSS at all. Thankfully, for #2, selectors-4 provides :has(), and it's simply up to the developers of selector libraries to implement it.

@BoltClock 2016-03-21 04:56:20

Actually, you know what, I made those stats up. It's probably more like 50-50, or 10-90, or something. The point is that, as now stated, this is just one solution that works for some people. But saying that "contrary to popular belief, there is in fact a previous sibling selector" is misleading at best, because it involves a layout technique, not a selector technique, which falls flat in use cases that don't involve CSS layout. This is why I've lately been much more picky about distinguishing between "pure CSS" and "pure CSS selectors".

@BoltClock 2016-03-21 05:05:34

Keep in mind that the CSS2.2 ED you're citing is, in essence, still CSS2. And flexbox and grid layout don't exist in CSS2, so as far as CSS2 is concerned, that information certainly holds true. At the very least, the text could be updated to mention that z-index may apply to other types of elements in future levels of CSS, the same way that it says other properties may establish a stacking context, such as opacity.

@Marat Tanalin 2016-03-21 09:34:16

@BoltClock My comment has nothing to do with browser support. The technique breaks semantics in favor of presentation. I believe a plain regular class added to previous-sibling element on server side is much more reasonable.

@Michael Benjamin 2016-03-21 10:37:51

@BoltClock, I appreciate your feedback. I see this entire thing from a practical perspective. And I wrote the answer for practical purposes. For developers who wish to target previous siblings on visual media, this technique may be useful. From the perspective of site users, previous siblings are being selected. So, for practical purposes, this can be deemed a previous sibling selector.

@Michael Benjamin 2016-03-21 10:42:07

From a technical perspective, I would agree this is not a PSS. But I generally try to provide answers that help solve real-world problems. I think this answer does that, using valid code and pure CSS.

@Rogier Spieker 2016-04-28 17:45:34

In case anyone is having trouble understanding when z-index will work, even when "omg, there's no position specified!", the specification mentions the concept of stacking context, which is explained nicely by this article on MDN

@Michael Benjamin 2016-04-28 17:48:32

@RogierSpieker, thanks for posting that MDN article. I read it a while back and it's very helpful. I also wrote this, which also tries to explain stacking contexts:

@Rogier Spieker 2016-04-28 17:57:30

@Michael_B you're welcome! I've dealt with a lot of front-enders unaware of this. One other thing I'd like to mention, the faux previous sibling selector also works nicely with float: right (or any other means to reverse the ordering, of which flex/order has little (least?) side effects). Whipped up two fiddles: demonstrating the float: right approach, and demonstrating direction: rtl

@Michael Benjamin 2016-04-28 18:05:23

@RogierSpieker, agreed. float:right is another method. I didn't mention it in my answer since it was already covered by at least two other answers to this question.

@Michael Benjamin 2017-03-04 03:48:50

@OzanKurt, a previous sibling selector is not possible in CSS. Therefore, all workarounds provided in these answers are obviously hacks or "cheats". Not sure what you were expecting.

@BoltClock 2018-02-05 05:58:01

It's a common misconception that selectors have anything to do with the cascade. Cascading, as defined by CSS, happens on a per-element basis. There is nothing in theory that would preclude the existence of a previous sibling selector or make it an oxymoron - especially now that Selectors has transcended Cascading Style Sheets altogether, rendering the CSS argument moot.

@Michael Benjamin 2018-03-11 22:38:12

Thanks for this clarification. I've removed that section from my answer and made other updates. @BoltClock

@Michael Benjamin 2018-03-11 22:39:23

Also, great analysis of CSS selectors utilized in non-CSS. I appreciate your separation of concerns argument and will keep it in mind. I also perused many of the links you referenced, including your whitespace in selectors, which was a useful refresher. Thanks, again.

@bkidd 2019-04-29 20:20:55

@Michael_B that was a gangster-level hack!

@MonteCristo 2020-05-10 16:48:46

@MichaelBenjamin what if the list is dynamic? I am setting the position of the child elements to be absolute. So order doesn't change the position. But it seems to break things? and styles not applied to all the children.

@Hung Tran 2020-05-16 09:40:00

Thanks for this. This is exactly what I needed.

@Danny van Holten 2020-07-02 08:27:43

Just want to mention this would severely damage a11y. You should NOT use this.

@Hejar 2018-02-23 16:38:00

I had a similar problem and found out that all problem of this nature can be solved as follows:

  1. give all your items a style.
  2. give your selected item a style.
  3. give next items a style using + or ~.

and this way you'll be able to style your current, previous items(all items overridden with current and next items) and your next items.


/* all items (will be styled as previous) */
li {
  color: blue;

/* the item i want to distinguish */
li.milk {
  color: red;

/* next items */
li ~ li  {
  color: green;

  <li class="milk">Milk</li>

Hope it helps someone.

@quetzalcoatl 2019-09-16 14:42:29

it's basically the same trick as in older answer from the same thread:

@Quentin 2013-03-19 15:19:46

Selectors level 4 introduces :has() (previously the subject indicator !) which will allow you to select a previous sibling with:

previous:has(+ next) {}

… but at the time of writing, it is some distance beyond the bleeding edge for browser support.

@Reed Martin 2017-01-20 07:59:42

"Bleeding edge for browser support" might be an overstatement. As of writing this, not even the latest version of Chrome can use the :has() pseudo-class.

@Quentin 2017-06-20 10:18:45

@ReedMartin — That's why I said some distance beyond the bleeding edge

@Arch Linux Tux 2018-02-15 15:02:51

":has is not marked as part of the dynamic selector profile, which means it can not be used within stylesheets; only with functions like document.querySelector()." -

@Jacob van Lingen 2020-02-12 11:57:25

@ArchLinuxTux: "This limitation is now removed", so once upon of time we possibly can use this feature :D.

@Quentin 2020-02-12 12:00:00

@JacobvanLingen — — No browser supports it at present.

@Jacob van Lingen 2020-02-13 07:23:18

@Quentin: I know. Arch Linux Tux quoted some old specification that states that the :has pseudo-class can only be used by JavaScript, because performance-wise it would be to heavy to implement this in CSS. That limitation in the spec is gone. You are right browsers still need to implement it though. So let's wait another few years...

@Vadim Ovchinnikov 2017-01-14 17:33:05

Another flexbox solution

You can use inverse the order of elements in HTML. Then besides using order as in Michael_B's answer you can use flex-direction: row-reverse; or flex-direction: column-reverse; depending on your layout.

Working sample:

.flex {
  display: flex;
  flex-direction: row-reverse;
   /* Align content at the "reversed" end i.e. beginning */
  justify-content: flex-end;

/* On hover target its "previous" elements */
.flex-item:hover ~ .flex-item {
  background-color: lime;

/* styles just for demo */
.flex-item {
  background-color: orange;
  color: white;
  padding: 20px;
  font-size: 3rem;
  border-radius: 50%;
<div class="flex">
  <div class="flex-item">5</div>
  <div class="flex-item">4</div>
  <div class="flex-item">3</div>
  <div class="flex-item">2</div>
  <div class="flex-item">1</div>

@Roko C. Buljan 2015-08-19 01:52:00

Two tricks. Basically inverting the HTML order of your desired elements in HTML and using
~ Next siblings operator:

float-right + inverse the order of HTML elements

div{ /* Do with the parent whatever you know just to make the
  inner float-right elements appear where desired */
  float:right;  /* float-right the elements! */
span:hover ~ span{ /* On hover target it's "previous";) elements */
  <!-- Reverse the order of inner elements -->

Parent with direction: rtl; + inverse the order of inner elements

  direction: rtl;
  display: inline-block; /* inline-block to keep parent at the left of window */
span:hover ~ span{ /* On hover target it's "previous";) elements */
Hover one span and see the previous elements being targeted!<br>

<div class="inverse">
  <!-- Reverse the order of inner elements -->

@DynamicDan 2014-02-07 16:13:58

Depending on your exact objective, there is a way to achieve the usefulness of a parent selector without using one (even if one were to exist)...

Say we have:

      <li><a>White socks</a></li>
      <li><a>Blue socks</a></li>

What can we do to make the Socks block (including sock colours) stand out visually using spacing?

What would be nice but doesn't exist:

ul li ul:parent {
  margin-top: 15px;
  margin-bottom: 15px;

What does exist:

li > a {
  margin-top: 15px;
  display: block;
li > a:only-child {
  margin-top: 0px;

This sets all anchor links to have 15px margin on the top and resets it back to 0 for those with no UL elements (or other tags) inside LIs.

@mantish 2015-01-16 22:45:45

I found a way to style all previous siblings (opposite of ~) that may work depending on what you need.

Let's say you have a list of links and when hovering on one, all the previous ones should turn red. You can do it like 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>

@A.L 2015-04-24 17:04:20

You can add an explanation of how it works. (it seems that you apply an style to all the items and to the following items but it can de described explicitly)

@Steven Vachon 2015-05-19 15:00:39

Awesome solution. No need to reorder the elements in markup nor in render (via float:right). It did require a white-space collapse between units/words and padding instead of margins, but it works perfectly otherwise!

@azerafati 2016-05-01 15:15:47

yea, but a single previous is needed most of the time NOT ALL the previous ones!

@Lynn 2016-08-01 08:19:16

The links all turn red if I hover over the space between them, for me.

@mantish 2016-08-04 10:23:55

@Lynn the answer only includes the code to make the previous links red on hover. Additional styles depend on your use case. For a star rating component (which I guess is a common case), you would need to get rid of that space and also make red the hovered link.

@rafibomb 2017-03-16 06:00:01

As demonstrated here: It totally works! Thanks!

@radiantshaw 2018-08-21 05:36:19

Can anyone suggest how to remove the "hover on space"?

@allez l'OM 2018-09-04 12:48:57

@Lynn I went by myself to the 'mantish' solution, and having what you did point out (space between) I was looking for an improvement. Still expecting something better, but it is acceptable.

@Jono Stewart 2018-10-06 11:09:44

@allezl'OM you could use a negative margin and replace it with a padding. If there is a tiny overlap, that may not work for your solution, but the above worked (at least in Chrome) to give each a after the first a margin-left:-5px and padding-left:5px

@wiktus239 2018-10-18 13:25:37

@Lynn @radiantshaw You can add pointer-events: none to the container and pointer-events: auto; to the individual links. Then the empty space will not trigger all to go red. The hover events from individual links however, should propagate to the parent anyway.

@kernel 2014-08-29 15:27:40

If you know the exact position an :nth-child()-based exclusion of all following siblings would work.

ul li:not(:nth-child(n+3))

Which would select all lis before the 3rd (e.g. 1st and 2nd). But, in my opinion this looks ugly and has a very tight usecase.

You also could select the nth-child right-to-left:

ul li:nth-child(-n+2)

Which does the same.

@Andrew Leyva 2014-08-12 19:39:48

There is no "previous" sibling selector unfortunately, but you can possibly still get the same effect by using positioning (e.g. float right). It depends on what you are trying to do.

In my case, I wanted a primarily CSS 5-star rating system. I would need to color (or swap the icon of) the previous stars. By floating each element right, I am essentially getting the same effect (the html for the stars thus must be written 'backwards').

I'm using FontAwesome in this example and swapping between the unicodes of fa-star-o and fa-star


.fa {
    display: inline-block;
    font-family: FontAwesome;
    font-style: normal;
    font-weight: normal;
    line-height: 1;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;

/* set all stars to 'empty star' */
.stars-container {
    display: inline-block;      

/* set all stars to 'empty star' */
.stars-container .star {
    float: right;
    display: inline-block;
    padding: 2px;
    color: orange;
    cursor: pointer;


.stars-container .star:before {
    content: "\f006"; /* fontAwesome empty star code */

/* set hovered star to 'filled star' */
    content: "\f005"; /* fontAwesome filled star code */

/* set all stars after hovered to'filled star' 
** it will appear that it selects all after due to positioning */
.star:hover ~ .star:before {
    content: "\f005"; /* fontAwesome filled star code */

HTML: (40)


@Wylliam Judd 2017-11-01 21:12:01

float right and + or ~ selectors strikes me as the cleanest work around.

@cletus 2009-11-30 04:08:54

No, there is no "previous sibling" selector.

On a related note, ~ is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector. + is for next sibling and is CSS2.1.

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

@Lie Ryan 2011-02-26 16:34:48

From the CSS3 standard: The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

@BoltClock 2011-03-29 21:05:10

@Lie Ryan: Yeah, but the point cletus is making in his answer is that you don't select the preceding element.

@Abacus 2013-07-17 18:26:30

Here's an example I made to see what this can, and can't, do.

@Satbir Kira 2015-05-18 21:11:49

The jquery function useful for this is prev(). For example $("#the_element").prev().css("background-color", "red")

@samnau 2018-04-18 14:09:53

Depending on your markup, this might help:…

@Brandon Roberts 2020-07-27 03:06:13

I'm going to try selecting all tags matching the "Previous Sibling" [GeneralTagSelector] :not([GeneralTagSelector] ~ [GeneralTagSelector] where the general tag selector references the set of nodes that includes your "Previous Sibling". If you don't want the first one add nth-child to both to target nth child but not any other ones, therefore matching your Node. If you wanted to add JS to determine order in a dynamic setting you could write a script to update your css, pass that to PHP and you can write files, if you wanted you could have an extra css like dynamicJsPHPGenerated.css

@Bryan Larsen 2011-11-30 16:40:40

I had the same question, but then I had a "duh" moment. Instead of writing

x ~ y


y ~ x

Obviously this matches "x" instead of "y", but it answers the "is there a match?" question, and simple DOM traversal may get you to the right element more efficiently than looping in javascript.

I realize that the original question was a CSS question so this answer is probably completely irrelevant, but other Javascript users may stumble on the question via search like I did.

@David 2013-02-12 19:14:20

I believe that works when y can be found easily. Problem is if y can only be found relative to x, and in reversing it, you can't find y because you have to find x first. This is of course in reference to the question of y being preceding sibling rather than next, but may also apply for y being a following sibling.

@Bryan Larsen 2013-03-13 09:04:10

You're being kind of harsh, Harsh. (sorry, couldn't resist.) The point is that sometimes you just need to know "does y exist?". Other times you can use ":before" to put something between the two elements. Finally, if you do have to drop into jQuery, using find("y ~ x").prev() is easier than many alternatives.

@Zenexer 2013-07-31 00:56:00

The idea of a previous sibling selector is that it will select the previous element. Unfortunately, reversing it, as described here, doesn't provide this functionality.

@Rajesh Paul 2013-11-03 05:21:31

@BryanLarsen Applying logic without testing properly. That's not expected even though your answer seems smart enough.

@Jaime Hablutzel 2014-04-23 21:20:06

Thanks @Zenexer for the clarification that this answer doesn't provide an actual solution to the original question, I was starting to feel myself stupid thinking about how y ~ x could solve my problem

@limitlessloop 2014-11-07 22:31:41

I don't see how this works, it's this the same y > x?

@Bryan Larsen 2014-11-10 13:08:34

You're right, @sevenupcan, it doesn't work. The point of this answer is to get people to ask themselves if they really need x ~ y, can they make y ~ x work for them? Some people can, some people can't. It often times it makes sense to re-examine your question while looking for an answer.

@Muhammad 2015-06-06 09:40:09

but I cannot using this when I am using the same tags but it is only possible when I have to use id , class or different tags

@BoltClock 2015-10-27 09:23:25

I understand the idea behind this answer, however the reasoning given in the answer doesn't quite make sense. The selector y ~ x doesn't answer the "is there a match?" question, because the two selectors given here mean completely different things. There is no way y ~ x could ever produce a match given the subtree <root><x/><y/></root> for example. If the question is "does y exist?" then the selector is simply y. If the question is "does y exist given a sibling x in any arbitrary position?" then you'd need both selectors. (Though maybe I'm just nitpicking at this point...)

@N73k 2019-05-18 17:45:02

This is wrong. This selects x's that come after y's. But what you want to do is select x's that come before y's.

Related Questions

Sponsored Content

18 Answered Questions

[SOLVED] Is there a CSS selector for elements containing certain text?

  • 2009-10-05 14:26:09
  • jantimon
  • 595095 View
  • 536 Score
  • 18 Answer
  • Tags:   css css-selectors

10 Answered Questions

[SOLVED] Which characters are valid in CSS class names/selectors?

  • 2009-01-15 23:37:39
  • Darryl Hein
  • 382600 View
  • 1212 Score
  • 10 Answer
  • Tags:   css css-selectors

33 Answered Questions

[SOLVED] Is there a CSS parent selector?

  • 2009-06-18 19:59:36
  • jcuenod
  • 2099270 View
  • 3240 Score
  • 33 Answer
  • Tags:   css css-selectors

10 Answered Questions

[SOLVED] not:first-child selector

  • 2012-09-05 21:09:16
  • Oto Shavadze
  • 818092 View
  • 825 Score
  • 10 Answer
  • Tags:   css css-selectors

11 Answered Questions

[SOLVED] What does the "+" (plus sign) CSS selector mean?

  • 2009-07-16 19:26:50
  • gday
  • 318121 View
  • 761 Score
  • 11 Answer
  • Tags:   css css-selectors

8 Answered Questions

[SOLVED] What does the ">" (greater-than sign) CSS selector mean?

  • 2010-07-12 04:33:08
  • Misha Moroshko
  • 204546 View
  • 478 Score
  • 8 Answer
  • Tags:   css css-selectors

5 Answered Questions

[SOLVED] What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

  • 2012-05-28 09:10:00
  • Akshat
  • 271270 View
  • 877 Score
  • 5 Answer
  • Tags:   css css-selectors

16 Answered Questions

[SOLVED] CSS selector for first element with class

  • 2010-04-26 22:51:13
  • Rajat
  • 1047146 View
  • 973 Score
  • 16 Answer
  • Tags:   css css-selectors

1 Answered Questions

[SOLVED] CSS Selector that applies to elements with two classes

  • 2010-09-22 18:06:16
  • Adam
  • 270429 View
  • 480 Score
  • 1 Answer
  • Tags:   css css-selectors

Sponsored Content