postcss / postcss-simple-vars

PostCSS plugin for Sass-like variables
MIT License
415 stars 36 forks source link

Use a variable in :nth-child(An+B) syntax #88

Closed sylbru closed 4 years ago

sylbru commented 4 years ago

Is there any way to use a variable inside the An+B clause in the :nth-child pseudo-selector? I want to have these selectors match the number of columns in my grid layout.

My current CSS (with the help of this article):

.grid {
   $columns: 3;
   display: grid;
   grid-template-columns: repeat($columns, 1fr);
   grid-gap: 2em;

   &__item {
      padding: 2em;
      border: 1px solid black;

      &:nth-child(-n+3) {
         border-top: 0;
      }
      &:nth-child(3n+1) {
         border-left: 0;
      }
      &:nth-child(3n) {
         border-right: 0;
      }
      &:nth-child(3n+1):nth-last-child(-n+3),
      &:nth-child(3n+1):nth-last-child(-n+3) ~ & {
         border-bottom: 0;
      }
   }
}
ai commented 4 years ago

Does it work?

&:nth-child($(columns)n) {
sylbru commented 4 years ago

Yes! It works perfectly, thank you! I knew there was some kind of string interpolation syntax, but I couldn’t find it.