Did you know that css has only 1 direction and that is forward? You can select next element with the + sign, even next siblings with the ~ sign, but there is no way to go backwards. Css does not have a method for the time being to select a previous element / elements (besides the :nth-last-child and :nth-last-of-type). For the css4 draft it was proposed a previous combinator / parent selector that could be marked with the ! sign. It would look like this:

   !h2 + h3 { padding-bottom:0 }

This will result in resetting the h2 padding value to 0 if after it there is an h3 tag. For now this is only science fiction.But then how to do it? There are some scenarios when we can simulate it with a reverse logic.
This logic is built upon the idea that you set on everything the style that you meant to put on the unreachable selectors(the previous siblings) and then reset to normal for the rest. Let’s see a practical use of this:

In the above picture you can see that we have a navigation and a bottom border that extends till the active item in the navigation. If we could select all previous siblings of the active element we would do just this:

   #navigation !li ~ li.active, #navigation li.active   { 
       border-bottom:3px solid #063078 
   }

We don’t have this option, so let’s see what we can do. Instead of using the include approach, better let’s use the exclude. First we set the bottom border on every li item in the navigation.

   #navigation li  { 
       border-bottom:3px solid #063078 
   }

Now we exclude the ones we don’t need with border bottom.

   #navigation li.active ~ li  { 
      border-bottom:none 
   }

That’s all the magic.

This method was for all the previous siblings of an element, but styling only the previous sibling would be difficult task, probably with the existing css methods even impossible. If we need to style the previous element on the click of the next element, that we can achieve with HTML and CSS.

   
First-element

After this we only declare in CSS the following:

   div:target { font-size:30px }

There you have it, targeting a previous element on click. This method is even good for selecting the parent on click, if you place the id on the elements parent.It might come handy sometimes.

Update

While I was writing another article, I remembered that actually there is a way to go backwards. Let’s suppose we have a list with numbers but in ascending order:

   
  • 5
  • 4
  • 3
  • 2
  • 1

When we use on the li elements a float:right rule, the whole list will reverse to descending order, well at least visually.

    ul {
       float:left;
       clear:both;
       margin:0;
       padding:0
    }
    ul li {
       float:right;
       list-style:none;
       padding:0 10px;
    }
    ul .active, ul .active ~ li {
       color:red
    }

Any comment is welcomed, so please leave a comment below.