logo

Center only one element using margin auto in CSS

February 1, 2024

Kevin Powell shared a nifty tiny trick to center only one element horizontally within its parent container using the margin property 👀.

You can set the margins left and right of the element you want to center to auto. This method relies on the parent element being a flex container.

Here's the demo 👇.

Your JS is turned off. Please turn it on to see the CodePen. Here's a screenshot from the Pen

Try reload the page, our check out the pen on CodePen.

The .center class will center the element in the space available because the auto margins distribute the available horizontal space equally on both sides of the element.