how to select two nth children in css
i have a container that contains 6 children, i want to select the 3rd and 4th children .
24 Replies
i know i could do div:nth-child(3), div:nth-child(4){}
but is there any way i could do it in one line of code
like div:nth-child(3,4)
this doesnt work
do those children have a class? and what are you trying to do?
maybe you're going about it the wrong way, and there could be an easier way
yes those children have the same class
all 6
same class
what are you trying to do?
https://preview.colorlib.com/theme/feliciano/index.html
like the menu section of this page
i want the middle row's children to be row-reverse
btw im not sure if colorlib is trustable site to visit
i always wanna pre-warn others so as to not get them in trouble
what that theme is doing is to manually put the content where it should be
if the image is on the left, the markup has the image on the left
if the image is on the right, the markup has the image on the right
with grid (subgrid in my case) and a little bit of js, you can loop over the items and check if the row is odd or not. and style according to it
https://codepen.io/MarkBoots/pen/mdYXzXN?editors=1111
(if im not mistaken they are working on css row/column selectors for grid, but probably will take a while)
it's also responsive and doesn't minds the amount of childs
https://jsfiddle.net/c3rm6yzg/ <-- you can hard-code it as well, or automatically generate it with sass
the trick is math
every
2*cols - [0..cols-1]
, you set the style
if you want 3 columns, it's 2*3n - [0..2]
-> [6n, 6n - 1, 6n - 2]
, which selects the 6th, 5th and 4th elements, and then the 12th, 11th and 10th, and then the 18th, 17th and 16th ... would achieve it in a single line but it isn't really that different to what you allready tried.
that doesn't work
it will work for 2 columns, but not for 3
I was really just answering the original question. I know it won't work for 3 columns but that wasn't what bonaventure was originally asking.
Both you and Mark have provided much more complete solutions, I was just concentrating on the original question.
yours is good for the exact solution, but it isn't very extensible in the future, and if you need 3 or 4 columns it will have to be re-written
mine is very loopable
I absolutely agree
i agree as well
but it is a nice trick, not gonna lie
yours has another problem: it only works for the 3rd and 4th, and doesn't select the 8th and 9th
which, again, for this exact question works fine
if only we had
:nth-row()
/ :nth-column()
we kinda do
:nth-child(n of .selector)
if js sets the class, for example, then it's done
but then, that's dumb and js can just set the class
wait, no, this makes no sense, ignore it
https://jsfiddle.net/c3rm6yzg/1/ <-- i remade this in sass and ... 😭 it was horrible!Was talking with Tab Atkins at CSS day and it sounds like we'll be able to select specific grid cells one of these days 😄
hopefully it works for tables too