With Pure CSS you cannot select previous sibling with css.
But you can select next sibling with next sibling +
selector i.e
li.active + li {
background: blue;
}
However in some cases you can make previous sibling to look like selected (But it has its limitations).
While for previous sibling if you just wants to apply background-color
on previous item, you can make previous items looks like selected with pseudo class i.e :before
or :after
of active element.
.list {
list-style: none;
overflow: hidden;
padding: 0;
margin: 0;
}
.list li {
position: relative;
padding: 3px 10px;
}
.list li.active {
background: green;
}
.list li.active:before {
position: absolute;
background:red;
height: 100%;
bottom: 100%;
content: '';
z-index: -1;
right: 0;
left: 0;
}
.list li.active + li {
background:blue;
}
<ul class="list">
<li>one</li>
<li>two</li>
<li class='active'>three</li>
<li>four</li>
<li>five</li>
<li>six</li>
</ul>
With JavaScript (jQuery Framework) you can select previous select previous sibling.
You can use jQuery's .prev()
method to select previous sibling i.e.
$('.list li.active').prev().addClass('prev');
$(function() {
$('.list li.active').prev().addClass('prev');
});
.list {
list-style: none;
padding: 0;
margin: 0;
}
.list li {
padding: 3px 10px;
}
.prev {
background: red;
}
.active {
background: green;
}
.active + li {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="list">
<li>one</li>
<li>two</li>
<li class='active'>three</li>
<li>four</li>
<li>five</li>
<li>six</li>
</ul>