Styles based on number of children

2019-02-19 10:46发布

问题:

I have a container (.homepage-section) and inside this there could be up to three .widget's. Depending on how many .widget's there inside of .homepage-section, I'd like the widths to change.

I've followed the approach outlined by Lea Verou (link) but with no success.

Here's the SASS function I've written (so far):

.widget {
     @for $i from 1 through 3 {
       &:first-of-type:nth-last-of-type(#{$i}),
       &:first-of-type:nth-last-of-type(#{$i}) ~ .widget {
         width: (1000px / #{$i});
       }
     }
  }

http://codepen.io/anon/pen/BKwte

回答1:

Try the following:

.widget {
  @for $j from 2 through 5 {
    @for $i from 1 through $j {
      &:nth-of-type(#{$j + 1 - $i}):nth-last-of-type(#{$i}),
      &:nth-of-type(#{$j + 1 - $i}):nth-last-of-type(#{$i}) ~ .widget {
        width: (1000px / $j);
      }
    }
  }
}

(see the edited pen).

The general rule — for each count of widgets, the sum of numbers in nth-* and nth-last-* must be the number of widgets plus 1, and the overall width must be divided by the number of widgets.



标签: css css3 sass