Lately i face a problem to keep my menu using 100% of the page width and at the same time keep the menu items equidistant, especially if you are using multiple media queries for large screens, then most of us will go to JS solutions.
Until i came throw an article Equidistant Objects with CSS by Chris Coyier with his nice way of explaining how to find the solution inspired me to find another solutions.
lets say we have N items with total actual width is Z px
So if we find the prefect margin X for each item to complete the total width to 100% For N number of items
we need 2*N of X (2 x for each item ) And because of the first and last items that should be on the edge of each side, we have to reduce 2 X
so we have ( N * 2 ) – 2 of X margin between the items to fill the space, lets call it Y Y = ( N * 2 ) – 2 N: number of the items We will get Zpx + X * Y = 100% X = ( 100 / Y )% – ( Z / Y )px here we face the problem of subtracting different units which we can solve it by using margin and padding to solve it like:
Padding = 100 / Y % Margin = – Z / Y px
and we chose margin for minus value because padding can’t take negative value. Notes:
- Using different font-family or font-size on different media queries may affect the total element width and break the equation.
- The easier way to find out the total width is to give all the items 0 margin and padding then keep reducing the page width until the items wrap down (the breaking point), with inspect element we can get the total width.
- For any reason you want to take off the float:left from <li> items then read this
- giving margin & padding 0 for the left side of first item and the right side of last item
lets say we have 4 items then
N = 4 ,
Y = 6 ,
Padding = 100 / Y % = 16.66%
Margin = – Z / Y px = 48.66px