I spend somewhere around 1.5 to 2 hours each day with some good ol' vanilla CSS, HTML and JS, today I decided to tackle the browser API known as IntersectionObserver. I primarily wanted to use IntersectionObserver to lazy load images efficiently. After I felt like I understood it, I wanted to make it so that all the odd images fade in from the left and the even ones from the right.
So my CSS looked like this:
img:nth-child(even) {
transform: translateX(50%);
}
img:nth-child(odd) {
transform: translateX(-50%);
}
I wrote a seperate class named fadeIn
that would be added to the classList
of each image when it's within the viewport, so fadeIn
looked like this:
.fadeIn {
transform: translateX(0%);
}
Which didn't work at all, I don't really know why, would like to hear from one of you readers as to why it didn't. Even though it didn't work, I had a hunch that it has to do with me using :nth-child
, and so I was scratching my head thinkin what I could do to select all the children of the fadeIn
class.
So I thought maybe if I look at the MDN docs for CSS selectors, I'd find something but I didn't atleast not something that could be used directly. I looked at each selector individually, their docs and I reached the docs for :not(). That's when it clicked! If I technically say that I don't want the children of a selector that doesn't exist or most likely wouldn't exist I would get all the children! Which resulted in this:
.fadeIn:not(x) {
transform: translateX(0%);
}
Which worked! Tadaaa...
Then I played with this block of css to see if it would select all the siblings even the nested ones and unfortunately (or fortunately in some situations) it doesn't.
Here is the codepen that I used! Check it out and see for yourself, maybe leave a heart/love on the pen if you liked it. This was my first blogpost in dev.to, all this time I lurked around reading. Appreciate any comments, specifically if this is something good or bad to do.
Thank you for reading!
Top comments (3)
The reason why applying
.fadeIn
didn't work is that it's less specific thanimg:nth-child(odd)
. If you change it toimg.fadeIn
(same specificity as the others) and make sure it's declared after theimg:nth-child(odd)
in your stylesheet, it should work fine!I see, that makes sense. Thanks a lot for reading and for the comment!
Oh... yep. The specificity rules.
(shudder)
Nam!
Sorry, that was my PTSD speaking.