Centering a dropdown menu with CSS calc()

I worked out a solution for centering a dropdown menu with CSS calc() that I couldn’t find elsewhere on the inter-webs. My issue was that I didn’t want to set an explicit width on the top-level nav items, and/so I couldn’t use a hard pixel value to offset & center the dropdowns.

See my example below, via Codepen:

See the Pen Centered Dropdown with CSS calc() by Bjorn Hagstrom (@bjornhagstrom) on CodePen.

This is the “magic” bit:

transform: translateX( calc( calc( 250px - 100% ) / -2) );

The calculation requires:

  • that the menu is set to the same width as it’s parent (100%),
  • and/also that the child link elements are set to a specific width (in my case, 250px)

Breaking it down further:

We subtract the width of the menu (100%, of its parent) from 250px (child link width), and then cut that in half (divide by 2*) to find the amount we want to move the sub-menu to keep things centered.

*And we’re using a -2 to to give us a negative px value, which will move the menu left!

Not very long ago, I might have used javascript to measure the widths of everything and do the calculations. But now with calc() we can do it right in CSS. And even better, since we used a transform, older browsers that don’t support it will just left-align the menu with it’s parent.

Pretty nifty!