Home > Enterprise >  Technically, why is this DIV centered, when top, bottom, left and right are zero?
Technically, why is this DIV centered, when top, bottom, left and right are zero?

Time:11-06

I am learning the many ways to center an element in the middle of the screen. I just discovered the code below, and I am trying to understand the technical explanation behind how it works.

<body>
   <div ></div>
</body>
.square{
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;

    margin: auto;

    background-color: pink;
    height: 50px;
    width: 50px;
}

At first, I thought if both top and bottom are zero, the element will be we vertically centered on the screen. Also if both left and right are zero, the element will be horizontally centered on the screen. But all this will not work without margin: auto. Can you help me understand how margin interacts with top, bottom, left and right?

CodePudding user response:

This div is in the center because you have set the margin to auto. what happens when you set margin to auto it will calculate the distance from all directions weather it is top, bottom, left, or right. the distance from each point will be same that's why the div is in center.

for example if we have to middle the webpage in horizontal center we give the webpage margin like this.

body {
margin:0 auto;
}

this will make the body equal distance from left and right side but it will give 0 margin on top and bottom.

CodePudding user response:

margin

The margin property is actually a shorthand property for the following individual margin properties:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

In margin auto, the element will take up the specified width, and the remaining space will be split equally between the left and right margins, similarly for the top and bottom.

  • Related