Centralizing using the absolute position

5

I do not understand the following code:

div{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    background: red;
}

Example online

I know that setting top: 0 and bottom: 0 and setting a width the element will stretch occupying height: 100% of the parent element, the same with left: 0 and right: 0 (correct me if I am wrong). But what I do not understand is the margin: auto , can someone explain to me how it will center the element in the center?

    
asked by anonymous 20.12.2016 / 06:35

2 answers

3

To center something in the center of the page there are several techniques.

Explaining margin its function as observed is to define a margin for some element, and when its value is auto it means that the browser will set the margin automatically, following example:

.quadrado{
  background-color: red;
  display: block;
  height: 100px;
  margin: 0 auto;
  width: 100px;
}
<div class="quadrado"></div>

Note that I am using margin: 0 auto zero represents margin-top and margin-bottom , and auto represents margin-left and margin-right is an abbreviation.

In my example the right and left margins are automatic and the browser automatically sets its positioning, and when the element is a block with defined width it centers horizontally.

To align horizontally and vertically I would use this technique:

body, .container, html{
  height: 100%;
}

.container{
  display: flex;
  align-items: center;
  justify-content: center;
}

.quadrado{
  background-color: red;
  display: inline-block;
  height: 100px;
  width: 100px;
}
<div class="container">
   <div class="quadrado"></div>
 </div>

Obs. When you set margin: auto you are assigning an automatic margin to top right bottom left

    
20.12.2016 / 12:57
0
div{
    position: absolute;
    left: 50%;
    margin-left: -50px;
    width: 100px;
    height: 100px;
    background: red;
}

This code snippet should solve your problem.

    
20.12.2016 / 20:58