Understanding Absolute position better

Understanding Absolute position better
0

#1

Hi everyone,
In the FCC Beta version => Applied visual design, the code in the snippet below is given to us. The .heart div has this positioning:

position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

Since there is no other item which is positioned, it is positioned relative to the body element. My question is: Why is it showing in the center of the screen? Is it because all sides “pull” the element to the same extent? Is it a good practice for centering elements?


#2

Wow, this is a really good question :smiley:
I didn’t know it at first until I read further. Someone asked the same question 2 years ago on StackOverflow apparently. It all made sense after reading the definition of what it is actually doing.

Essentially, the left, right, top and bottom is setting a new boundary for the content to be center.
Here is a codepen of what it meant. You gonna need to look at it in full view.
Perfect Centering


#3

Thank you! After experimenting with your pen I would like to add this - As you said the ‘top’, ‘right’, ‘bottom’ and ‘left’ properties set the boundaries, but it is the margin: auto which centers the element within the boundaries, both horizontally and vertically.


#4

Yes, when you say margin:auto it will center your content, so that its it. :slight_smile: