DEV Community

Cover image for CSS: Absolute center element

CSS: Absolute center element

Jim Raptis on November 20, 2019

TLDR: Learn how to center an element with position: absolute inside its parent. Introduction You should probably be thinking, β€œWhy not u...
Collapse
 
melmacaluso profile image
Mel Macaluso

How's that better than the following? Just being curious as I always opt for the following if for some very specific reason flexbox is not the option πŸ˜‚:

  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  margin: auto;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
d__raptis profile image
Jim Raptis

One more CSS instruction I guess 🀣It seems clear and straightforward though, I liked it πŸ’ͺ

Collapse
 
link2twenty profile image
Andrew Bone

My most up voted stack overflow answer was about this 😁

top:0 (default)

By default, your element is at the top of the page, and the top of the element is at 0:

--------Top of Page--------
{element}


------Middle of  Page------



------Bottom of  Page------

top:50%

When you move it down by 50% height (50% of the entire page), the top of the…

Collapse
 
d__raptis profile image
Jim Raptis

Nice detailed answer. It's a tricky topic πŸ’ͺ

Collapse
 
nuong profile image
nuong.nguyen

Nice, thank for sharing

Collapse
 
d__raptis profile image
Jim Raptis

Really happy you liked it 😊

Collapse
 
trevdev profile image
Trev

The "wat" image just about killed me. Seriously nice tip, has come in handy for me often!

Collapse
 
d__raptis profile image
Jim Raptis

hahaha glad you liked Trev 😊

Collapse
 
thehumble_angy profile image
Ange Kouakou

That's clever 🀩

Collapse
 
d__raptis profile image
Jim Raptis

Thanks man πŸ‘

Collapse
 
nwajeigideon profile image
Nwajei Gideon • Edited

Sometimes i make use of

Margin: 0 auto;

Or

I could just place the element i want centered in a center tag

<\center>
Collapse
 
jwp profile image
JWP

Doesn't grid do this automatically with justify-items:center?

Collapse
 
d__raptis profile image
Jim Raptis

Sure! Grid or flexbox are my main ways to go too.

However, this little hack comes in handy when I need to position an element relative to its parent.
i.e. an "X" icon at the top right corner of an image.

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman

Resize the window until reached half of the screen, you will see an unwanted scrollbars.