Given a HTML element with some silibings:
<div id=parent>
<div></div>
<div></div>
<div></div>
...
<div id=fourthToLast></div>
<div></div>
<div id=penultimate></div>
<div></div>
</div>
The penulimate and the fourthToLast silibing are special:
One or the other – but never both – should be shown at different widths,
depending on media breakpoints and total number of silibings.
In the CSS code I put pseudo code selectors:
silibingNrOf(#penultimate) mod x = y
Example: If parent has a total of 15 silibings, then silibingNrOf(#penultimate) is 14.
silibingNrOf(#penultimate) mod 3 would equal 2.
I need the correct CSS selector syntax for this problem and can’t find out how to do it.
#fourthToLast, #penultimate { display: none; }
@media screen and (min-width: 400px) {
if silibingNrOf(#penultimate) mod 2 = 0 {
#penultimate { width: 25%; display: block; }
}
@media screen and (min-width: 800px) {
#penultimate { display: none; }
if silibingNrOf(#penultimate) mod 3 = 2 {
#penultimate { width: 33%; display: block; }
}
if silibingNrOf(#penultimate) mod 3 = 0 {
#fourthToLast { width: 16.666%; display: block; }
}
}
}
2
Answers
Given the structure from the question and all it's variations with 1 to 7 elements (+ the extra elements 'penultimate' and 'fourthToLast'). The empty elements formerly labeled 'penultimate' and 'fourthToLast' don't need an ID for this.
The task is
To be solved without javascript and without functions not widely supported by all browsers (:has() / Firefox).
Solution:
Special thanks go to David Thomas for his very inspiring jsfiddle that put me on track.
Edit: you could use
:nth-of-type(3n)
forsilibingNrOf(#penultimate) mod 3 = 0
and:nth-of-type(3n+2)
forsilibingNrOf(#penultimate) mod 3 = 2
. And obviously:nth-of-type(even)
or:nth-of-type(2n)
forsilibingNrOf(#penultimate) mod 2 = 0
as you’ve already figured out. :nth-child() would also work for this case, and the parameters would be the same. I jumped straight to javascript in my first answer and only thought of this after your comment.Previous answer:
You could do the following in javascript:
and then use these classes to select the elements in your sass code. Also, penultimate and fourthToLast could be selected using :nth-last-child pseudoselector.