I have a question about 'margin' and 'position'

Tell us what’s happening:
Why when I remove the ‘margin: auto’ attribute, the ‘.heart’ element moves to the top left corner. I still don’t understand how this works because according to the code below I used the ‘position’ attribute and set the value to top, left, right and bottom. So why did I still need to use more margin when I used position?

Your code so far

  .heart {
    position: absolute;
    margin: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: pink;
    height: 50px;
    width: 50px;
    transform: rotate(-45deg);
    animation-name: beat;
    animation-duration: 1s;
<div class="heart"></div>

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/78.0.136 Chrome/72.0.3626.136 Safari/537.36.

Link to the challenge:

They don’t give us enough info to know how everything works just the parts we’re supposed to change. margin: auto; is suppose center the element within the parent by applying equal margin in all four directions when the element is in the normal flow of the document. position removes the element from the normal document flow. Isn’t an absolute position zero pixels from the top, zero pixels from the right, zero pixels from the bottom, and zero pixels from the left actually four different positions? Shouldn’t they cancel each other out or center the element? I’d like to think that the the base style would be

margin: auto;
height: 50px;
width: 50px;

then the content before and after would be position: relative; with the corresponding right and left adjustment.
Since it does work we need to get a deep understanding of CSS elsewhere, perhaps the specification?

There is a Smashing Magazine article that tries to explain this centering technique. I’d suggest also checking out the comment section.

1 Like