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:
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!