Explain Codes LogoExplain Codes Logo

How to center a "position: absolute" element

html
responsive-design
css-positioning
flexbox
Alex KataevbyAlex Kataev·Aug 26, 2024
TLDR

To center an absolutely positioned element, apply CSS styles with top and left set to 50% and use transform property to adjust the element's position by half of its size: translate(-50%, -50%).

.centered { position: absolute; top: 50%; left: 50%; /* move it back by half, like a reverse flash⚡ */ transform: translate(-50%, -50%); }

Then add the .centered class to your HTML tag to center it within its parent, like a well-behaved kid who got a lollipop 🍭.

Strategies for the bulls-eye

Just like in archery, sometimes different strategies are needed to hit the bulls-eye. Depending on the specific layout or design requirements, here are alternate techniques for centering an element:

Centering with 'margin:auto' missiles

Fire the margin: auto missiles, with left and right (or top and bottom) set to 0. But make sure your element has defined width (or height), otherwise, it'll be like shooting blanks 😅.

.horizontal-auto-center { position: absolute; left: 0; right: 0; width: 100px; /* autopilot engaged */ margin-left: auto; margin-right: auto; }

Negative Margin, the Jedi way

Push the element to the left 50% and then bring it back with a negative margin-left. Remember to specify a width; otherwise, your Jedi trick will fail.

.jedi-center { position: absolute; left: 50%; width: 100px; /* The force is strong with this one */ margin-left: -50px; }

Flexbox, The 'Avengers Assembled' way

To assemble all the children within our parent element like a well-drilled team, let's call upon the all-powerful Flexbox:

.shields-up-flex { /* Flex, I choose you */ display: flex; justify-content: center; align-items: center; }

The epic saga of centering

New hope: Grid layout

When faced with dynamic content, the Jedi Grid layout emerges as our savior, handling the dark side of undefined dimensions.

Revenge of the overflow

With absolute positioning, beware of the content overflowing its container. Use overflow: hidden or use Flexbox to avoid this trap.

Return of the z-index

An absolutely positioned element, like a Sith lord, may secretly overlap other elements. Use z-index wisely to maintain peace in your galaxy.