0

is there a way to use the n of nth-of-type to calculate some style?

I am making a photo slider and a part of the css currently looks like this:

.container *:nth-of-type(1) img{
  object-position: 0%;
}
.container *:nth-of-type(2) img{
  object-position: calc(100% / 9 * 1);
}
.container *:nth-of-type(3) img{
  object-position: calc(100% / 9 * 2);
}
.container *:nth-of-type(4) img{
  object-position: calc(100% / 9 * 3);
}
.container *:nth-of-type(5) img{
  object-position: calc(100% / 9 * 4);
}
.container *:nth-of-type(6) img{
  object-position: calc(100% / 9 * 5);
}
.container *:nth-of-type(7) img{
  object-position: calc(100% / 9 * 6);
}
.container *:nth-of-type(8) img{
  object-position: calc(100% / 9 * 7);
}
.container *:nth-of-type(9) img{
  object-position: calc(100% / 9 * 8);
}
.container *:nth-of-type(10) img{
  object-position: 100%;
}

this is easy to generate with js but I would love a css only solution. Is this possible?

codepen

Sam Apostel
  • 593
  • 3
  • 18
  • you need to use SASS/LESS, no way with only CSS OR re-think your layout to make the CSS easier – Temani Afif Aug 27 '18 at 09:45
  • 1
    What is the desired layout you are looking for? Pretty sure there is another way of doing this entirely without involving complex calculations. – Esko Aug 27 '18 at 09:45
  • You can do this with a simple Sass loop http://thesassway.com/intermediate/if-for-each-while – Vinicius Cainelli Aug 27 '18 at 09:46
  • esko, I updated my question with a codepen – Sam Apostel Aug 27 '18 at 09:47
  • There is *counter* in CSS, but it's not usable anywhere except `:before{content}`. https://stackoverflow.com/questions/43539203/use-css-counter-in-calc – Justinas Aug 27 '18 at 09:48
  • @Justinas that's not exactly true. (The usability part).. Using it on `::before` selectors is just a convention (and often most practical). But it is just as valid syntax on any other selector – Samuel Hulla Aug 27 '18 at 09:55
  • @SamApostel Is the object-position there so that the left side of the picture is shown when not hovering? Is that the meaning if it? – Esko Aug 27 '18 at 10:08
  • I know SASS and LESS exist but was trying to find something more vanilla – Sam Apostel Aug 27 '18 at 10:09
  • @Esko yes, so that when you start hovering, the image that expands, expands from the sides and the middle won't move – Sam Apostel Aug 27 '18 at 10:10
  • @SamApostel I removed the calculations and a few other css-rules and I think it still has the same effect: https://codepen.io/anon/pen/OoNxjZ What do you think? Hmm not 100% though just noticed a little difference... – Esko Aug 27 '18 at 10:13
  • @Esko that's what happens when you uncheck the checkbox, thus I already explored that ;p. this is not the effect I'm looking for – Sam Apostel Aug 27 '18 at 10:16
  • @SamApostel I get it now, not as easy as it seemed :) – Esko Aug 27 '18 at 10:16

0 Answers0