Pure CSS Solution
Two Pure CSS Solutions
Solution 1
- Make the parent node (
<body>
in this case) a flex column container
- Change
.title:nth-child(odd)
to (even)
- Assign
order: 3
to the adjacent sibling .test + div
Explanation
Because .test
is still in the HTML, it will always be considered to be in the odd position hence changing the shading pattern to even rectifies that situation.
Using the order
flexbox property allows us to visually move a tag, but as far as the HTML code itself, the positions are still the same. Placing the 4th div into the 3rd visibly doesn't change it to become odd, it will retain the shade of an even tag.
Soilution 2
- Make all
<div>
color:transparent
- Assign each dive a
::before
pseudo-class content:n
n=original position number/for 3+ offset by +1
- All
div::before
color:#000
Explanation
This solution uses ::Before
to present the title of what's in that position rather than what is actually there. So 1
and 2
are accurate but at the third position it is now 4
and so on. The last title is display:none
instead of position 3
.test
. This complex solution came about when JosephSible brought to my attention that the titles weren't in order so Solution 1 "doesn't work", while I beg to differ since the OP never mentioned order, Solution 2 isn't broken. Please review Demo2.
Demo 1
<!DOCTYPE html>
<html>
<head>
<style>
body {
display: flex;
flex-flow: column nowrap;
}
.title:nth-child(even) {
background: #ddd;
}
.test {
display: none;
}
.test+div {
order: 3
}
</style>
</head>
<body>
<div class='title'>lorem</div>
<div class='title'>lorem</div>
<div class='title test'>lorem</div>
<div class='title'>lorem</div>
<div class='title'>lorem</div>
<div class='title'>lorem</div>
<div class='title'>lorem</div>
</body>
</html>
Demo 2
<!DOCTYPE html>
<html>
<head>
<style>
.title:nth-child(even) {
background: #ddd;
}
div {
color: transparent;
}
.test {
background: #ddd;
}
div:first-of-type::before {
content: '1';
}
div:nth-of-type(2)::before {
content: '2';
}
.test::before {
content: '4'
}
.test+div::before {
content: '5'
}
.test+div+div::before {
content: '6'
}
.test+div+div+div::before {
content: '7';
}
.test+div+div+div+div {
display: none;
}
div::before {
color: #000
}
</style>
</head>
<body>
<div class='title'>1</div>
<div class='title'>2</div>
<div class='title test'>3</div>
<div class='title'>4</div>
<div class='title'>5</div>
<div class='title'>6</div>
<div class='title'>7</div>
</body>
</html>