Skip to content

Instantly share code, notes, and snippets.

@75th
Created May 23, 2012 22:10
Show Gist options
  • Save 75th/2778129 to your computer and use it in GitHub Desktop.
Save 75th/2778129 to your computer and use it in GitHub Desktop.
LESS: Items of varying width side-by-side, filling up a fixed width
/*
* Sometimes, with a horizontal navigation menu, you need the items
* to vary in width, but to all fill up a predetermined width.
*
* Doing this with normal CSS involves annoying, tedious arithmetic,
* and making changes is painful.
*
* This snippet uses LESS to make maintaining such a menu easy.
*/
@item-1: 10; // First, define the relative proportion of each link's width.
@item-2: 10; //
@item-3: 10; // It doesn't matter what they add up to, as it's all based on percentages.
@item-4: 10; //
@item-5: 11; // If you find that your initial values are not visually pleasing,
@item-6: 8; // you can adjust them one-at-a-time without worrying about compensating elsewhere.
@total: @item-1 + @item-2 + @item-3 + @item-4 + @item-5 + @item-6; // Find the total of the above arbitrary values.
@width: 940px; // This is the width that you need the items to fill up.
@item-1-width: round(((@item-1 / @total) * @width)); // Now, use MATHEMATICS to find out how wide each item should be.
@item-2-width: round(((@item-2 / @total) * @width));
@item-3-width: round(((@item-3 / @total) * @width));
@item-4-width: round(((@item-4 / @total) * @width));
@item-5-width: round(((@item-5 / @total) * @width));
@item-6-width: round(((@item-6 / @total) * @width));
/*
* It's possible that some rounding errors crept in during the previous step.
*
* Let's find out how many extra pixels we need to add or subtract from one of the items.
*/
@extra: @width - (@item-1-width + @item-2-width + @item-3-width + @item-4-width + @item-5-width + @item-6-width);
@padding-and-border: 2px; // The sum of left and right border width and padding on each item.
/*
* Now just set the widths!
*/
&#item-1 {
width: @item-1-width - @padding-and-border;
}
&#item-2 {
width: @item-2-width - @padding-and-border;
}
&#item-3 {
width: @item-3-width - @padding-and-border;
}
&#item-4 {
width: @item-4-width - @padding-and-border;
}
&#item-5 {
width: @item-5-width - @padding-and-border;
}
&#item-6 {
width: @item-6-width - @padding-and-border + @extra; // Don't forget to adjust for rounding errors.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment