Skip Navigation
Madison, Wisconsin
Powderkeg Web Design
June 16, 2017

Sass Function for Dynamic Equal Sized Elements

Nick
Nick
Sass Function for Dynamic Equal Sized Elements

If you’ve ever wanted some Sass (SCSS) to show equal width elements regardless of how many there are, then look no further!

Imagine you want to make a menu of equal width items. The client might have 3 things, or the client might have 9 things. The end result is they still want each item to take up the same width. Obviously it won’t work very well on smaller screen with a insanely large amount of items, but this does the trick:

ul {
   li {
      /*Equal width items*/
      @for $i from 1 through 20 {
         &:first-child:nth-last-child(#{$i}),
         &:first-child:nth-last-child(#{$i}) ~ li {
	    width: 100% / $i } 
      }
   }
}

What you’re seeing here is a Sass function that find how many <li> elements there are and output a sibling selector (~) based off the last element to target them and give them all equal widths based on 100 / how many elements there are total. The end number in the “from 1 through 20” is just how high you want it to iterate. It basically adds for unnecessary css if you make the number a lot higher than what you feasibly would want them to actually display on the front end.

Obviously, you’ll want to take consideration for different screen sizes since a mobile device show 12 things wide won’t be the best of sights. All in all, it’s a pretty nifty end result for essentially 5 lines of css! This should work in all modern browsers.

Nick Kalscheur

Nick Kalscheur

Lead Developer