January 6, 2013

Fixed Element Width: Percent of a Percent

On a recent project, and again while building v3.0 of this site, I needed to calculate the percent width of an element set to position: fixed. The task was tricky because all of the column widths were percents.

The Riddle

.container is 70% of the window, and .sidebar is 20% of .container. The percent of a fixed element is calculated from the window, not the parent. Find the percent which makes .nav_fixed the same width as .sidebar.


The Answer

Setting .sidebar to 20% won’t work; it’s too large at 20% of the windows width. We need to figure out the size of .sidebar in relation to the window, which is 20% of 70%.

The quick answer: multiply 20×70, then move the decimal left two places. 14% is the width of .nav_fixed.

And, here’s the math behind the answer:


Credit goes to Michael Cohen and his video on Percent of Percent, in which he gives a better explanation.