I have a list of items which overlap slightly. The stacking order of elements inside this list should be as follows: the first element should appear on top, and the last element should appear at the bottom.
The result should look like this:
Here is my first attempt, but the overlap happens in the wrong direction:
ul {
list-style: none;
padding-left: 0;
display: flex;
}
.circle {
background-color: black;
color: white;
border-radius: 50%;
width: 50px;
height: 50px;
display: flex;
align-items: center;
justify-content: center;
border: 5px solid white;
margin-right: -14px;
}
<ul>
<li>
<div class="circle">1</div>
</li>
<li>
<div class="circle">2</div>
</li>
<li>
<div class="circle">3</div>
</li>
</ul>
I understand this is because the default z-index
behaviour follows the order of DOM elements: elements that appear later in the DOM will appear above elements before.
One workaround would be to manually apply a unique z-index
to each list item, but this would not scale if the list was dynamic in length (number of items).
Another workaround would be to use flex-direction: row-reverse
, but then the items would be in the wrong order. We could fix this by changing the DOM order, but this would break the HTML semantics.
I am interested to know if there's a solution which (1) works for all list sizes and (2) doesn't require changing the order of elements in the DOM/HTML.