I was able to write a JavaScript carousel and thought it might be more compact to use CSS transitions with nth-child selectors like this:
img {
transition: all 1s linear; /* or corresponding vendor prefixes */
position:absolute;
}
img:nth-child(1) {
top: 0%;
left: 0%;
}
img:nth-child(2) {
top: 0%;
left: 50%;
}
/*and so on...*/
The items would then be rotated by appending the first child or prepending the last child of the container:
parent.appendChild(parent.children[0]);
This approach works well for all but the appended element. It is removed entirely and then reattached, so it ends up in the right spot but does not use the transition effect. Is there a way to use CSS transitions even when relocating an element in the DOM?
jsFiddle Demo – Click the document to advance the images.
I ended up using a
data-*attribute and selector. It is a little more verbose thannth-child, but has the advantage of working. It is also cleaner than parsing through class lists.Each element has a
data-orderattribute, which can be assigned with HTML or JavaScript:Replace
nth-childwith the attribute selector:When rotating, increment the order in the dataset. This seems to update the attribute, even though we are modifying the property:
Here is the final result.